# Leetcode [No.34] Find First and Last Position of Element in Sorted Array (Medium) ## 題目 Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value. If target is not found in the array, return [-1, -1]. You must write an algorithm with O(log n) runtime complexity. ## 思路 + 一看到這個題目,有修過資料結構的同學應該可以馬上知道至少需要使用binarySearch。 + 但binarySearch有非常多的眉角,我在這裡使用左閉右開的定義! + 先找到其中之一的結果後,再去重新計算最左的值,因為一array有可能會是重複的值。 + 計算完左邊換計算右邊 + 最後return結果就行了~ ```c++ class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { int front = 0; int end = nums.size(); vector<int>sol; int ans = (binarySearch(nums,front,end,target)); if(ans == -1) {sol.emplace_back(-1);sol.emplace_back(-1);return sol;} int new_front = 0; int new_end = 0; for(int i = front; i <= ans; i++) { if(nums[i] == target) { new_front = i; break; } } for (int i = end-1; i >= ans; i--) { if(nums[i] == target) { new_end = i; break; } } sol.emplace_back(new_front);sol.emplace_back(new_end); return sol; } int binarySearch(vector<int>& nums, int front, int end, int target) { while(front < end) { int mid = (front+end)/2; if(nums[mid] == target) { return mid; } else if (nums[mid] > target) { end = mid; } else // nums[mid] < target { front = mid+1; } } return -1; } }; ``` ### 解法分析 + time complexity: O(lgn+n) ### 執行結果 ![](https://hackmd.io/_uploads/SJFEgXZ-T.jpg)