658. 找到 K 个最接近的元素
题目:
思路:
【1】这道题的核心在于找到X的值或者距离X值之间差值最小的值,然后往两边进行扩散,差值最小的优先纳入。
代码展示:
//时间3 ms 击败99.5% //内存43.8 MB 击败 79.45% class Solution { public List<Integer> findClosestElements(int[] arr, int k, int x) { int right = binarySearch(arr, x); int left = right - 1; while (k-- > 0) { if (left < 0) { right++; } else if (right >= arr.length) { left--; } else if (x - arr[left] <= arr[right] - x) { left--; } else { right++; } } List<Integer> ans = new ArrayList<Integer>(); for (int i = left + 1; i < right; i++) { ans.add(arr[i]); } return ans; } public int binarySearch(int[] arr, int x) { int low = 0, high = arr.length - 1; while (low < high) { int mid = low + (high - low) / 2; if (arr[mid] >= x) { high = mid; } else { low = mid + 1; } } return low; } } //时间0 ms 击败 100% //内存44 MB 击败 42.69% import java.util.AbstractList; class Solution { public List<Integer> findClosestElements(int[] arr, int k, int x) { int left=0; int right=arr.length-k; List<Integer> list = new ArrayList<>(); while(left<right){ int temp=left+(right-left)/2; if(x - arr[temp] > arr[temp + k] - x){ left=temp+1; }else { right=temp; } } int finalI = left; return new AbstractList<Integer>() { @Override public Integer get(int index) { return arr[index+ finalI]; } @Override public int size() { return k; } }; } }