• [leetcode]Search for a Range


    二分查找。找到后往左往右移。又说有种log(n)的算法是二分查找最左的,然后二分查找最右的。省却最后那部分O(n)的

    public class Solution {
        public int[] searchRange(int[] A, int target) {
            // Start typing your Java solution below
            // DO NOT write main() function
            int pos = searchTarget(A, target, 0, A.length -1);
            if (pos == -1) return new int[]{-1,-1};
            
            int start = 0;
            int end = A.length - 1;
            for (int i = pos - 1; i >= 0; i--) {
                if (A[i] != target) {
            		start = i+1;
            		break;
            	}       		
            }
            for (int i = pos + 1; i < A.length; i++) {
            	if (A[i] != target) {
            		end = i - 1;
            		break;
            	}
            }
            return new int[]{start,end};
        }
        
        public int searchTarget(int[] A, int target, int left, int right) {
        	if (left > right) return -1;
        	int mid = (left + right) / 2;
        	if (A[mid] == target) return mid;
        	if (A[mid] > target) return searchTarget(A, target, left, mid -1);
        	else return searchTarget(A, target, mid+1, right);   	
        }
    }
    

    这是参考答案,两次log(n)的查找:http://discuss.leetcode.com/questions/213/search-for-a-range

    class Solution {
    public:
        vector<int> searchRange(int A[], int n, int target) {
            vector<int> range(2, -1);
            int lower = 0;
            int upper = n;
            int mid;
    
            // Search for lower bound
            while (lower < upper) {
                mid = (lower + upper) / 2;
                if (A[mid] < target)
                    lower = mid + 1;
                else
                    upper = mid;
            }
    
            // If the target is not found, return (-1, -1)
            if (A[lower] != target)
                return range;
            range[0] = lower;
    
            // Search for upper bound
            upper = n;
            while (lower < upper) {
                mid = (lower + upper) / 2;
                if (A[mid] > target)
                    upper = mid;
                else
                    lower = mid + 1;
            }
            range[1] = upper - 1;
    
            return range;
        }
    };
    

      

  • 相关阅读:
    jvm误区--动态对象年龄判定
    jmeter入门实例
    七牛云的文件上传和下载
    layer.prompt添加多个输入框
    zero copy图解
    java枚举的线程安全及序列化
    java单例模式
    ubuntu16.04 python3.5 opencv的安装与卸载(转载)
    独家git clone 加速方法
    apt get update无法正常使用解决方案(转载)
  • 原文地址:https://www.cnblogs.com/lautsie/p/3235760.html
Copyright © 2020-2023  润新知