Leetcodes Solution 34 Search for a Range

匯總

雪之下雪乃:leetcode解題總匯?

zhuanlan.zhihu.com圖標

思路1

用二分搜索分別找到最小和最大的索引

Search for a Range - LeetCode

class Solution{public: vector<int> searchRange(vector<int>& nums, int target){ int n = nums.size(); int i = 0, j = n-1; vector<int> ret(2, -1); if (n == 0) return ret; //Search for the left one while(i < j){ int mid = (i + j) / 2; if(nums[mid] < target) i = mid + 1; else j = mid; } if(nums[i] != target) return ret; else ret[0] = i; //Search for the right one j = n-1; //we dont have to set i to 0 the seond time. while(i < j){ int mid = (i + j) / 2 + 1; //make mid biase to the right if(nums[mid] > target) j = mid - 1; else i = mid; } ret[1] = j; return ret; }};

推薦閱讀:

Google面試題 | 循環字元串裡面的獨立子串
九章演算法 | Facebook面試題:最大平均值子數組2
浙江大學-數據結構-希爾排序-9.2.1
浙江大學-數據結構-小白專場:C語言實現如何建立圖-6.5.3
浙江大學-數據結構-選講Huffman Codes-7.4.2

TAG:演算法 | 數據結構 | 編程 |