Array
Two Pointers
Binary Search
Sorting
Sliding Window
Heap (Priority Queue)
Description
Given a sorted integer array arr
, two integers k
and x
, return the k
closest integers to x
in the array. The result should also be sorted in ascending order.
An integer a
is closer to x
than an integer b
if:
|a - x| < |b - x|
, or
|a - x| == |b - x|
and a < b
Example 1:
Input: arr = [1,2,3,4,5], k = 4, x = 3
Output: [1,2,3,4]
Example 2:
Input: arr = [1,1,2,3,4,5], k = 4, x = -1
Output: [1,1,2,3]
Constraints:
1 <= k <= arr.length
1 <= arr.length <= 104
arr
is sorted in ascending order.
-104 <= arr[i], x <= 104
Solutions
Solution 1: Sort
Python3 Java C++ Go TypeScript Rust
class Solution :
def findClosestElements ( self , arr : List [ int ], k : int , x : int ) -> List [ int ]:
arr . sort ( key = lambda v : abs ( v - x ))
return sorted ( arr [: k ])
1
2
3
4
5
6
7
8
9
10
11
12
13
14 class Solution {
public List < Integer > findClosestElements ( int [] arr , int k , int x ) {
List < Integer > ans = Arrays . stream ( arr )
. boxed ()
. sorted (( a , b ) -> {
int v = Math . abs ( a - x ) - Math . abs ( b - x );
return v == 0 ? a - b : v ;
})
. collect ( Collectors . toList ());
ans = ans . subList ( 0 , k );
Collections . sort ( ans );
return ans ;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 int target ;
class Solution {
public :
static bool cmp ( int & a , int & b ) {
int v = abs ( a - target ) - abs ( b - target );
return v == 0 ? a < b : v < 0 ;
}
vector < int > findClosestElements ( vector < int >& arr , int k , int x ) {
target = x ;
sort ( arr . begin (), arr . end (), cmp );
vector < int > ans ( arr . begin (), arr . begin () + k );
sort ( ans . begin (), ans . end ());
return ans ;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 func findClosestElements ( arr [] int , k int , x int ) [] int {
sort . Slice ( arr , func ( i , j int ) bool {
v := abs ( arr [ i ] - x ) - abs ( arr [ j ] - x )
if v == 0 {
return arr [ i ] < arr [ j ]
}
return v < 0
})
ans := arr [: k ]
sort . Ints ( ans )
return ans
}
func abs ( x int ) int {
if x >= 0 {
return x
}
return - x
}
1
2
3
4
5
6
7
8
9
10
11
12 function findClosestElements ( arr : number [], k : number , x : number ) : number [] {
let l = 0 ;
let r = arr . length ;
while ( r - l > k ) {
if ( x - arr [ l ] <= arr [ r - 1 ] - x ) {
-- r ;
} else {
++ l ;
}
}
return arr . slice ( l , r );
}