LeetCode34. Find First and Last

2018-10-23  本文已影响5人  来世不做友人A

题目---二分题

Given an array of integers nums sorted in ascending order, 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].

Example 1:
Input: nums = [5,7,7,8,8,10], target = 8
Output: [3,4]
Example 2:
Input: nums = [5,7,7,8,8,10], target = 6
Output: [-1,-1]

题目的大意是给定一个有序数组和一个目标数,求此目标数在数组中的起始位置。
代码贴上:

class Solution {
    public int[] searchRange(int[] nums, int target) {
        if(nums.length==0)
            return new int[]{-1,-1};
        int start = searchBoundary(nums,target);
        int end = searchBoundary(nums,target+1);
        //target不存在
        if(nums[start]!=target)
            return new int[]{-1,-1};
        if(nums[end]!=target)
            end = end-1;
        return new int[]{start,end};
    }
    
    //使用二分求开始位
    public int searchBoundary(int[] nums,int target){
        int lo = 0;
        int hi = nums.length-1;
        while(lo<hi){
            int mid = (lo+hi)/2;
    //如何控制停留再开始位的边界判断
            if(nums[mid]<target)
                lo = mid +1;
            else
                hi = mid;
        }
        return hi;
    }
}

此题一看就想到应该用二分的思想,设计二分算法去求得一个数在数组中的起始,,可分两步走:

上一篇 下一篇

猜你喜欢

热点阅读