zoukankan      html  css  js  c++  java
  • [leetcode] Search for a Range

    思路:就是二分查找,只是查找一个数的范围,思路和二分查找相似,只是在mid查找到此数后,利用right-- 或 left++ 寻找该数的右边界和左边界。

    Java代码如下:

        public int[] searchRange(int[] nums, int target) {
            int[] result = {-1, -1};
            int left = 0, right = nums.length - 1;
            while (left <= right) {
                if (nums[left] == target && nums[right] == target) { //when find both left index and right index, return.
                    result[0] = left;
                    result[1] = right;
                    return result;
                }
                int mid = (left + right)/2;
                if (nums[mid] == target) {
                    
                    if (nums[right] != target) {  // this if and else is very important! 
                        right--;
                    }
                    else {
                        left++;
                    }
                    
                }
                else if (nums[mid] > target) {
                    right = mid - 1;
                }
                else {
                    left = mid + 1;
                }
            }
            return result;
        }
  • 相关阅读:
    Mint linux中调整屏幕亮度的方法
    poj 1085 Triangle War (状压+记忆化搜索)
    CF1060F Shrinking Tree
    leetcode492
    leetcode258
    leetcode226
    leetcode371
    leetcode104
    leetcode389
    leetcode448
  • 原文地址:https://www.cnblogs.com/lasclocker/p/4713755.html
Copyright © 2011-2022 走看看