[LeetCode]Search for a Range

Search for a Range

My Submissions
Total Accepted: 62397 Total Submissions: 225032 Difficulty: Medium

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].

Subscribe to see which companies asked this question



這個題目還是二分查找的變形,首先要找到一個mid使得nums[mid]==targer,從而左右再用二分查找開始尋找,

public class Solution {

	public int[] searchRange(int[] nums, int target) {
        int [] result = new int[2];
        result[0]=-1;result[1]=-1;
        int head = 0;int tail = nums.length-1;
        while(head<=tail){
        	int mid = head+(tail-head)/2;
        	if(nums[mid]==target){
        		int i=head;int j = mid;
        		while(i<j){
        			int mid1 = i+(j-i)/2;
        			if(nums[mid1]<target){
        				i=mid1+1;
        			}
        			else{
        				if(j==mid1)break;
        				j=mid1;
        			}
        		}
        		result[0]=j;
        		i=mid;j=tail;
        		
        		while(i<j){
        			if(nums[j]==target){
            			i=j;
            			break;
            		}
        			int mid1 = i+(j-i)/2;
        			if(nums[mid1]>target){
        				j=mid1-1;
        			}
        			else{
        				if(i==mid1){
        					break;
        				}
        				i=mid1;
        			}
        		}
        		result[1]=i;
        		return result;
        	}
        	else{
        		if(nums[mid]>target){
        			tail=mid-1;
        		}
        		else{
        			head=mid+1;
        		}
        	}
        }
        return result;
    }

}


發佈了232 篇原創文章 · 獲贊 17 · 訪問量 44萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章