leetcode:658. Find K Closest Elements

Given a sorted array, two integers k and x, find the k closest elements to x in the array. The result should also be sorted in ascending order. If there is a tie, the smaller elements are always preferred.

Example 1:

Input: [1,2,3,4,5], k=4, x=3
Output: [1,2,3,4]

 

Example 2:

Input: [1,2,3,4,5], k=4, x=-1
Output: [1,2,3,4]

 

Note:

  1. The value k is positive and will always be smaller than the length of the sorted array.
  2. Length of the given array is positive and will not exceed 104
  3. Absolute value of elements in the array and x will not exceed 10

思路1:

因为数组是有序的,所以最后返回的n个元素也一定是有序的,最后返回的是一个长度为k的子数组,也就是从n个元素的数组中去掉n-k个元素,且去掉的元素肯定从数组两头开始去,因为距离x最远的元素肯定在首尾出现。

实现1:

import java.util.List;
import java.util.ArrayList;
class Solution {
    public List<Integer> findClosestElements(int[] arr, int k, int x) {
        List<Integer> ret=new ArrayList<Integer>();
        int len=arr.length;
        int left=0,right=len-1;
        while(len>k){
            if(Math.abs(x-arr[left])>Math.abs(arr[right]-x)){
                left++;
            }else{
                right--;
            }
            len--;
        }
        for(int i=left;i<=right;i++){
            ret.add(arr[i]);
        }
        return ret;
    }
}

 

思路2:

参考https://blog.csdn.net/TheSnowBoy_2/article/details/77441914

特殊情况:k个最近的元素都出现在数组的最左端或者都出现在最右端

通常,我们认为x出现在数组的中间,

假如我们取了 A[i] ~ A[i + k -1]. 
我们可以二分查找 i 计算 x - A[mid]和 A[mid +k] - x的距离 
如果x - A[mid] > A[mid + k] - x, 那就意味着 A[mid + 1] ~ A[mid + k] 肯定比 A[mid] ~ A[mid + k - 1]距离x更近,此时我们让left = mid + 1.

实现2:

import java.util.List;
import java.util.ArrayList;
class Solution {
    public List<Integer> findClosestElements(int[] arr, int k, int x) {
        List<Integer> list=new ArrayList<Integer>();
        int left=0,right=arr.length-k;
        while(left<right){
            int mid=left+(right-left)/2;
            if(Math.abs(x-arr[mid])>Math.abs(arr[mid+k]-x)){
                left=mid+1;//mid到x的距离大于mid+k到x的距离,右移
            }else{
                right=mid;//否则,左移
            }
        }
        for(int i=left;i<left+k;i++){
            list.add(arr[i]);
        }
        return list;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值