Leetcode-658 Find K Closest Elements(找到 K 个最接近的元素)
1 class Solution 2 { 3 public: 4 int myBinarySearch(vector<int> arr,int target) 5 { 6 int le = 0; 7 int ri = arr.size()-1; 8 while(le <= ri) 9 { 10 int mid = (le+ri)/2; 11 if(arr[mid] < target) 12 le = mid + 1; 13 else if(arr[mid] > target) 14 ri = mid - 1; 15 else 16 return mid; 17 } 18 return ri >= 0 ? ri : 0; 19 } 20 vector<int> findClosestElements(vector<int>& arr, int k, int x) 21 { 22 int oriIndex = myBinarySearch(arr,x); 23 24 int le,ri; 25 le = oriIndex; 26 ri = oriIndex+1; 27 int targetDiff = 0; 28 29 30 vector<int> result; 31 for(int i = targetDiff; targetDiff <= 100000; targetDiff ++) 32 { 33 while(le>=0 && abs(x-arr[le])==targetDiff) 34 { 35 result.push_back(arr[le]); 36 k --; 37 le --; 38 39 if(!k) 40 break; 41 } 42 if(!k) 43 break; 44 45 while(ri<=arr.size()-1 && abs(x-arr[ri])==targetDiff) 46 { 47 result.push_back(arr[ri]); 48 49 k --; 50 ri ++; 51 if(!k) 52 break; 53 } 54 if(!k) 55 break; 56 } 57 58 sort(result.begin(),result.end()); 59 return result; 60 } 61 };