// invirants: // If the target value is within the array to be searched, at any iteration, it stays within [left,right]
// [0, nums.length - 1] is our seaching range // keep searching until left > right where there is no element left in our range // mid = (left + right) / 2
/* if nums[mid] > target, since all the elements left in our range are valid, * thus right = mid - 1, as the mid value is impossible to be target now, * which is the same with updating the left index. */
classSolution { publicintsearch(int[] nums, int target) { intans= -1; intleft=0, right = nums.length - 1; int mid;
while(left <= right) { mid = (right - left)/2 + left; if (nums[mid] == target) { ans = mid; break; }elseif (nums[mid] > target ) { right = mid - 1; }else { left = mid + 1; } }
classSolution { publicintremoveElement(int[] nums, int val) {
intleftIndex=0; intrightIndex= nums.length - 1; // note: when left = right, the current pointing element has not // been checked, thus when and only when left > right, we stop checking while (leftIndex <= rightIndex) { if (nums[leftIndex] != val) { leftIndex ++; }else { nums[leftIndex] = nums[rightIndex]; rightIndex--; } }
return leftIndex; }
/* [0, nums.length) * */ // public int removeElement(int[] nums, int val) {
// int leftIndex = 0; // int rightIndex = nums.length;
/* * try to find the first element in this array which fit a[i] >= target * i.e. nums[pos - 1] < target <= nums[pos] */
// @lc code=start class Solution { // public int searchInsert(int[] nums, int target) { // int left = 0; // int right = nums.length - 1; // int mid = 0;