Repository navigation
Expand file tree
/
Copy pathproblem658.java
More file actions
108 lines (82 loc) · 2.33 KB
/
Copy pathproblem658.java
File metadata and controls
108 lines (82 loc) · 2.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
// 658. Find K Closest Elements
import java.util.*;
class Problem658{
public static List<Integer> findClosestElements(int[] arr, int k, int x) {
Problem658 obj = new Problem658();
int near= obj.findNearest(arr, x);
int left=near;
int right= near+1;
List<Integer> list = new ArrayList<>();
while(k>0 && (left>=0 && right<arr.length))
{
int left_abs=Math.abs(x-arr[left]);
int right_abs= Math.abs(x-arr[right]);
if(left_abs<=right_abs)
{
list.add(arr[left]);
left--;
k--;
}
else
{
list.add(arr[right]);
right++;
k--;
}
}
while (left>0 && k>0) {
list.add(arr[left]);
k--;
left--;
}
while(right<arr.length && k>0)
{
list.add(arr[right]);
right++;
k--;
}
Collections.sort(list);
return list;
}
public int findNearest(int a[],int target)
{
int left=0,right=a.length-1;
int ans=0;
while(left<right)
{
int mid=(left+right)/2;
if(target==a[mid]) // if you find target return target
return mid;
if(target>a[mid])
{
left=mid+1;
}
else
{
right=mid;
}
}
left--; // to find the left and right are indeces range where the target is present
if(left<0) // it the target is between 0 and 1 indece "left-- = -1" so
{
left=0;
}
int l_abs=Math.abs(target-a[left]);
int r_abs=Math.abs(target-a[right]);
if(l_abs<=r_abs)
ans=left;
else
ans=right;
return ans;
}
public static void main(String[] args)
{
int [] n2= {1,2,3,4,5};
List<Integer> list = findClosestElements(n2,4,3);
for(int i=0;i<list.size();i++)
{
System.out.print(list.get(i)+" ");
}
return;
}
}