classSolution{ publicintsearch(int[] nums, int target){ // 避免当 target 小于nums[0] nums[nums.length - 1]时多次循环运算! if (target < nums[0] || target > nums[nums.length - 1]) { return -1; } int left = 0, right = nums.length - 1; while (left <= right) { int mid = left + ((right - left) >> 1); //右移一位就是除2 if (nums[mid] < target) left = mid + 1; elseif (nums[mid] > target) right = mid - 1; elsereturn mid; } return -1; } }
第二种:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
classSolution{ publicintsearch(int[] nums, int target){ int left = 0; int right = nums.length; // 定义target在左闭右开的区间里,所以右边的开边界不用减一 while(left < right){ int mid = left + (right-left)/2; if (nums[mid] < target){ left = mid +1; } elseif (nums[mid] > target){ right = mid ; } elsereturn mid; } return -1; } }
// 滑动窗口 publicintminSubArrayLen(int s, int[] nums){ int left = 0; int sum = 0; int result = Integer.MAX_VALUE; for (int right = 0; right < nums.length; right++) { sum += nums[right]; while (sum >= s) { result = Math.min(result, right - left + 1); sum -= nums[left++]; } } return result == Integer.MAX_VALUE ? 0 : result; } }