Leetcode之Find First and Last Position of Element in Sorted Array
阿新 • • 發佈:2019-01-03
題目:
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]
程式碼:
vector<int> searchRange(vector<int>& nums, int target) { vector<int> res = { -1,-1 }; if (nums.size() == 0)return res; int i = 0, j = nums.size() - 1,mid=-1; if (nums[j]<target || nums[i]>target)return res; while (i <= j) { mid = (i + j) / 2; if (nums[mid] < target) { i = mid + 1; } else if (nums[mid] > target) { j = mid - 1; } else { while (nums[i] < target)i++; while (nums[j] > target)j--; res[0] = i; res[1] = j; break; } } return res; }
注:
先找其中的一個,找到以後左右縮小範圍。
注意考慮特殊情況,當nums.size==0的時候,直接返回[-1,-1]