34. 在排序数组中查找元素的第一个和最后一个位置
题目链接: https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
解题思路:
有序数组都用二分法,前后找。
1 class Solution { 2 public int[] searchRange(int[] nums, int target) { 3 int [] result = new int[]{-1,-1}; 4 5 int mid; 6 int start =0; 7 int end = nums.length-1; 8 if(nums.length==0||target<nums[0] || target>nums[end]) 9 return result; 10 //找最小 11 while(start<=end) 12 { 13 mid = start+(end-start)/2; 14 if(target==nums[mid]) 15 { 16 result[0] = mid; 17 end = mid-1; 18 } 19 else if(target>nums[mid]) 20 { 21 start = mid+1; 22 } 23 else 24 { 25 end = mid-1; 26 } 27 } 28 29 start =0; 30 end = nums.length-1; 31 32 //找最大 33 while(start<=end) 34 { 35 mid = start+(end-start)/2; 36 if(target==nums[mid]) 37 { 38 result[1] = mid; 39 start = mid+1; 40 } 41 else if(target>nums[mid]) 42 { 43 start = mid+1; 44 } 45 else 46 { 47 end = mid-1; 48 } 49 } 50 51 return result; 52 53 54 55 } 56 }