-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay_05.java
More file actions
64 lines (61 loc) · 1.68 KB
/
Copy pathDay_05.java
File metadata and controls
64 lines (61 loc) · 1.68 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
// Flood Fill
class Solution {
public void dfs(int[][] image, int sr, int sc, int color,int val) {
image[sr][sc] = color;
int n = image.length;
int m = image[0].length;
for(int i=0;i<2;i++){
int nrow = (i%2==0) ? sr + 1 : sr - 1;
int ncol = (i%2==0) ? sc + 1 : sc - 1;
if(nrow >= 0 && nrow < n && image[nrow][sc] == val){
dfs(image,nrow,sc,color,val);
}
if(ncol>= 0 && ncol < m && image[sr][ncol] == val){
dfs(image,sr,ncol,color,val);
}
}
}
public int[][] floodFill(int[][] image, int sr, int sc, int color) {
int n = image.length;
int m = image[0].length;
int val = image[sr][sc];
if(val == color) return image;
dfs(image,sr,sc,color,val);
return image;
}
}
// Pow(x, n)
class Solution {
public double pow(double x, long n){
if(n == 0) return 1;
if(n == 1) return x;
if(n % 2 == 0) return pow(x*x,n/2);
return x * pow(x,n-1);
}
public double myPow(double x, int n) {
long num = n;
if(num<0) return 1/pow(x,-num);
return pow(x,num);
}
}
// Majority Element
class Solution {
public int majorityElement(int[] nums) {
int n = nums.length;
int cnt = 0, maj = -1;
for(int i=0;i<n;i++){
if(cnt == 0){
cnt = 1;
maj = nums[i];
}
else if(nums[i] == maj) cnt++;
else cnt--;
}
cnt = 0;
for(int i=0;i<n;i++){
if(nums[i] == maj) cnt++;
}
if(cnt > (n/2)) return maj;
return -1;
}
}