zoukankan      html  css  js  c++  java
  • LeetCode 34 Search for a Range

    Given a sorted array of integers, find the starting and ending position of a given target value.

    Your algorithm's runtime complexity must be in the order of O(log n).

    If the target is not found in the array, return [-1, -1].

    For example,
    Given [5, 7, 7, 8, 8, 10] and target value 8,
    return [3, 4].

    思路;使用折半查找,首先看能不能找到target这个值,若不能则返回[-1,-1],若能。则再递归的查找左边界和右边界。
    public class Solution {
    	public int[] searchRange(int[] A, int target) {
    		int[] result = new int[] { -1, -1 };
    		int left = 0;
    		int right = A.length - 1;
    		int middle;
    
    		while (left <= right) {
    			middle = (left + right) / 2;
    			if (A[middle] > target) {
    				right = middle - 1;
    			} else if (A[middle] < target) {
    				left = middle + 1;
    			} else {
    				result[0] = searchLeft(A, left, middle, target);
    				result[1] = searchRight(A, middle, right, target);
    				return result;
    			}
    		}
    		return result;
    	}
    
    	private int searchLeft(int[] A, int begin, int end, int target) {
    		int left = begin;
    		int right = end;
    		int middle;
    
    		while (left < right) {
    			middle = (left + right) / 2;
    			//搜索左边界的前提是数组中已经存在target,
    			//而且參数传递经来的是数组值不大于target的部分
    			//故不须要检查A[middle]是否比target大
    			//仅仅须要比較A[middle]是否比target小或者相等
    			if (A[middle] < target) {
    				left = middle + 1;
    			} else {
    				return searchLeft(A, left, middle, target);
    			}
    		}
    		return left;
    	}
    
    	private int searchRight(int[] A, int begin, int end, int target) {
    		int left = begin;
    		int right = end;
    		int middle ;
    
    		while (left < right) {
    			middle = (left + right) / 2;
    			//搜索右边界的前提是数组中已经存在target,
    			//而且參数传递经来的是数组值不小于target的部分
    			//故不须要检查A[middle]是否比target小
    			//仅仅须要比較A[middle]是否比target大或者相等
    			if (A[middle] > target) {
    				right = middle - 1;
    			} else {
    				//注意这比searchLeft多的一部分。
    				//为了防止 A={8,9},target=8或者 A={8,8},target=8这一类情况
    				if (middle == left && A[right] > target)
    					return left;
    				if (middle == left && A[right] == target)
    					return right;
    				return searchRight(A, middle, right, target);
    			}
    		}
    		return left;
    	}
    }


  • 相关阅读:
    人月神话阅读笔记之二
    人月神话阅读笔记之三
    人月神话阅读笔记之一
    清楚浮动的10种方法
    WEB颜色值得设定
    文件上传 FileReader()
    Git学习笔记(三)
    Git学习使用笔记(二)
    Git使用学习笔记 (一)
    小知识点(JS)
  • 原文地址:https://www.cnblogs.com/yangykaifa/p/7074221.html
Copyright © 2011-2022 走看看