[leetcode]34. Find First and Last Position of Element in Sorted Array
阿新 • • 發佈:2018-12-01
自己寫的,雖然過了,但是其實是有問題的
class Solution { public int[] searchRange(int[] nums, int target) { if(nums==null||nums.length==0)return new int[]{-1,-1}; int n=nums.length; int low=0; int hi=n-1; int leftplace=-1; int rightplace=-1; if(nums[n-1]==target)rightplace=n-1; if(nums[0]==target)leftplace=0; while(low<=hi){ int mid=(low+hi)/2; if(low==hi){ if(nums[low]<=target-1){ leftplace=hi+1; if(leftplace<n&&nums[leftplace]!=target) leftplace=-1; break; } if(nums[low]==target){ leftplace=low; break; } } if(nums[mid]>target-1){ hi=mid-1; } else if(nums[mid]<target-1){ low=mid+1; } else{ leftplace=mid+1; break; } } while(leftplace>=0&&leftplace<n&&nums[leftplace]<target){ leftplace++; } if(leftplace>=0&&leftplace<n&&nums[leftplace]!=target) leftplace=-1; if(leftplace==n)leftplace=-1; low=0; hi=n-1; while(low<=hi){ int mid=(low+hi)/2; if(low==hi){ if(nums[hi]>=target+1){ rightplace=hi-1; if(rightplace>=0&&nums[rightplace]!=target) rightplace=-1; break; } if(nums[low]==target){ rightplace=low; break; } } if(nums[mid]>target+1){ hi=mid-1; } else if(nums[mid]<target+1){ low=mid+1; } else{ rightplace=mid-1; break; } } while(rightplace<n&&rightplace>=0&&nums[rightplace]>target){ rightplace--; } if(rightplace>=0&&rightplace<n&&nums[rightplace]!=target) rightplace=-1; return new int[]{leftplace,rightplace}; } }
Solution 1:找最左邊的和最右的後一個
當low==hi的時候退出,low每次除去比target小的部分,hi每次都在比target稍大的位子
class Solution { // returns leftmost (or rightmost) index at which `target` should be // inserted in sorted array `nums` via binary search. private int extremeInsertionIndex(int[] nums, int target, boolean left) { int lo = 0; int hi = nums.length; while (lo < hi) { int mid = (lo + hi) / 2; if (nums[mid] > target || (left && target == nums[mid])) { hi = mid; } else { lo = mid+1; } } return lo; } public int[] searchRange(int[] nums, int target) { int[] targetRange = {-1, -1}; int leftIdx = extremeInsertionIndex(nums, target, true); // assert that `leftIdx` is within the array bounds and that `target` // is actually in `nums`. if (leftIdx == nums.length || nums[leftIdx] != target) { return targetRange; } targetRange[0] = leftIdx; targetRange[1] = extremeInsertionIndex(nums, target, false)-1; return targetRange; } }