LeetCode 658. Find K Closest Elements(java)

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:
The value k is positive and will always be smaller than the length of the sorted array.
Length of the given array is positive and will not exceed 104
Absolute value of elements in the array and x will not exceed 104

我的解法:类似于暴力解,时间复杂度很高,思路就是:二分找到x在数组里的插入位置,再在数组里的那个位置向左和向右看,每次加进去一个,直到加满k个,这个方法不是很推荐,但是还是给个代码吧:
    public List<Integer> findClosestElements(int[] arr, int k, int x) {
        List<Integer> result = new ArrayList<>();
        if (arr.length == 0) return result;
        int index = findInsert(arr, x);
        int count = 1, i = 1;
        result.add(arr[index]);
        int left = index - 1;
        int right = index + 1;
        while (count < k) {
            if (left < 0) {
                result.add(arr[right]);
                right++;
                count++;
            } else if (right > arr.length - 1 || arr[right] - x >= x - arr[left]) {
                result.add(0, arr[left]);
                left--;
                count++;
            } else {
                result.add(arr[right]);
                right++;
                count++;
            }
        }
        return result;
    }
    public int findInsert(int[] arr, int x) {
        int begin = 0;
        int end = arr.length - 1;
        while (begin < end) {
            int mid = begin + (end - begin) / 2;
            if (x == arr[mid]) {
                return mid;
            } else if (x > arr[mid]) {
                begin = mid + 1;
            } else {
                end = mid - 1;
            }
        }
        return begin;
    }
解法二:这个解法是直接从数组里通过二分法找到应为的subarray的start位置,通过判断mid位置和mid + k位置上与x的差值的大小比较来确定二分的update rule,因此时间复杂度更好。
public List<Integer> findClosestElements(int[] arr, int k, int x) {
        List<Integer> res = new ArrayList<>();
        int start = 0, end = arr.length-k;
        while(start<end){
            int mid = start + (end-start)/2;
            if(Math.abs(arr[mid]-x)>Math.abs(arr[mid+k]-x)){ 
                start = mid+1;
            } else {
                end = mid;
            }
        }
        for(int i=start; i<start+k; i++){
            res.add(arr[i]);
        }
        return res;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值