Wednesday, March 13, 2019

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.
'''
class Solution(object):
    def findClosestElements(self, arr, k, x):
        """
        :type arr: List[int]
        :type k: int
        :type x: int
        :rtype: List[int]
        """
        if k > len(arr): return arr
        if k == 0: return []
     
        subarr = []
        for i in arr:
            if i > x:
                subarr.append([i,i-x])
            else:
                subarr.append([i,x-i])
     
        subarr = sorted(subarr, key = lambda y: y[1])
        result = [i[0] for i in subarr[:k]]
        result.sort()
        return result

    def findClosestElements(self, arr, k, x):
        """
        :type arr: List[int]
        :type k: int
        :type x: int
        :rtype: List[int]
        """
        if k > len(arr): return arr
        if k == 0: return []
       
        arr = sorted(arr, key = lambda y: abs(y-x))
        arr = arr[:k]
        arr.sort()
        return arr

No comments:

Post a Comment