classSolution { public: inthIndex(vector<int>& citations){ // given ascwnding order reverse(citations.begin(), citations.end()); int n = citations.size(); int l = 0, r = n-1; // 找出最小的索引其數值小於其索引 // - // 0 1 2 3 4 // 6 5 3 1 0 // - // 0 1 2 // 100 2 1 while(l<=r){ int mid = l +(r-l)/2; if(citations[mid] > mid) l = mid+1; else r= mid-1; } return l; } };
option 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution { public: inthIndex(vector<int>& citations){ // given ascending order int n = citations.size(); int l = 0, r = n-1; while(l<=r){ int mid = l +(r-l)/2; if (citations[mid] == n - mid) return n - mid; elseif (citations[mid] > n - mid) r = mid - 1; else l = mid + 1; } return n-l; } };