Skip to content

Commit cc7844f

Browse files
committed
Binary-search
1 parent 90fcc13 commit cc7844f

File tree

4 files changed

+139
-0
lines changed

4 files changed

+139
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
class Solution {
2+
public:
3+
vector<int> findClosestElements(vector<int>& arr, int k, int x) {
4+
5+
int pos=-1;
6+
int left=0, right=arr.size()-1;
7+
int n=arr.size();
8+
9+
if(x<arr[0])
10+
return vector<int>(arr.begin(),arr.begin()+k);
11+
else if(x>arr[n-1])
12+
return vector<int>(arr.begin()+(n-k),arr.end());
13+
14+
15+
while(left<=right)
16+
{
17+
int mid=left+(right-left)/2;
18+
19+
if(arr[mid]<=x)
20+
{
21+
pos=mid;
22+
left=mid+1;
23+
24+
}
25+
else
26+
right=mid-1;
27+
}
28+
29+
vector<int> res;
30+
31+
32+
33+
left=pos; right=pos+1;
34+
while(k--)
35+
{
36+
int left_diff=INT_MAX, right_diff=INT_MAX;
37+
38+
if(left>=0)
39+
left_diff=abs(x-arr[left]);
40+
41+
if(right<arr.size())
42+
right_diff=abs(x-arr[right]);
43+
44+
45+
if(left_diff<=right_diff)
46+
{
47+
res.push_back(arr[left]);
48+
left--;
49+
}
50+
else
51+
res.push_back(arr[right++]);
52+
53+
54+
}
55+
sort(res.begin(),res.end());
56+
return res;
57+
58+
59+
60+
61+
}
62+
};
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution {
2+
public:
3+
char nextGreatestLetter(vector<char>& letters, char target) {
4+
5+
int n=letters.size();
6+
if(target>=letters[n-1] || target<letters[0])
7+
return letters[0];
8+
9+
int left=0,right=n-1;
10+
int pos=-1;
11+
while(left<=right)
12+
{
13+
int mid=left+(right-left)/2;
14+
15+
if(letters[mid]>target)
16+
{
17+
pos=mid;
18+
right=mid-1;
19+
}
20+
else
21+
left=mid+1;
22+
}
23+
24+
return letters[pos];
25+
}
26+
};
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution {
2+
public:
3+
bool isPerfectSquare(int num) {
4+
5+
if(num==1)
6+
return true;
7+
8+
9+
10+
int low=1,high=num/2;
11+
12+
while(low<=high)
13+
{
14+
int mid=low+(high-low)/2;
15+
16+
if(mid==num/mid && num%mid==0)
17+
return true;
18+
else if(mid<num/mid)
19+
low=mid+1;
20+
else
21+
high=mid-1;
22+
}
23+
24+
return false;
25+
}
26+
};

Leetcode/Math/my-pow.cpp

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution {
2+
public:
3+
double myPow(double x, int n) {
4+
5+
if(x==1)
6+
return 1;
7+
8+
if(n==0)
9+
return 1;
10+
if(n<0)
11+
{
12+
if(n==INT_MIN) //this is to handle the case t avoid overflow of INT_MIN on -ve to +ve
13+
n+=2;
14+
15+
n=-n;
16+
x=1/x;
17+
return myPow(x,n);
18+
}
19+
20+
if(n%2==0)
21+
return myPow(x*x, n/2);
22+
else
23+
return x*myPow(x*x, n/2);
24+
}
25+
};

0 commit comments

Comments
 (0)