-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay_22.java
More file actions
103 lines (93 loc) · 2.56 KB
/
Copy pathDay_22.java
File metadata and controls
103 lines (93 loc) · 2.56 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
// Reverse Pairs
class Solution {
public int merge(int low,int mid,int high,int[] nums){
int cnt = 0;
int left = low, right = mid + 1;
int i = low, j = mid + 1;
List<Integer> temp = new ArrayList<>();
while(left<=mid && right<=high){
if(nums[left]<=nums[right]){
temp.add(nums[left++]);
}
else{
temp.add(nums[right++]);
}
}
while(left<=mid) temp.add(nums[left++]);
while(right<=high) temp.add(nums[right++]);
while(i<=mid && j<=high){
if((long)nums[i]>2*(long)nums[j]){
cnt+=(mid-i+1);
j++;
}
else{
i++;
}
}
for(i=low;i<=high;i++){
nums[i] = temp.get(i-low);
}
return cnt;
}
public int mergesort(int low,int high,int[] nums){
int cnt = 0;
if(low>=high) return cnt;
int mid = low - (low-high)/2;
cnt+=mergesort(low,mid,nums);
cnt+=mergesort(mid+1,high,nums);
cnt+=merge(low,mid,high,nums);
return cnt;
}
public int reversePairs(int[] nums) {
int n = nums.length;
return mergesort(0,n-1,nums);
}
}
// Detect a cycle in undirected graph --> GFG
class Solution {
public boolean dfs(int node,int parent, boolean[] vis,List<List<Integer>> adj){
vis[node] = true;
for(var it : adj.get(node)){
if(!vis[it]){
if(dfs(it,node,vis,adj)) return true;
}
else if(parent != it) return true;
}
return false;
}
public boolean isCycle(int V, int[][] edges) {
List<List<Integer>> adj = new ArrayList<>();
for(int i=0;i<V;i++){
adj.add(new ArrayList<>());
}
for(var it : edges){
adj.get(it[0]).add(it[1]);
adj.get(it[1]).add(it[0]);
}
boolean[] vis = new boolean[V];
for(int i=0;i<V;i++){
if(!vis[i]){
if(dfs(i,-1,vis,adj)) return true;
}
}
return false;
}
}
// Count Primes
class Solution {
public int countPrimes(int n) {
int cnt = 0;
boolean[] prime = new boolean[n];
for(int i=2;i*i<n;i++){
if(!prime[i]){
for(int j=i*i;j<n;j+=i){
prime[j] = true;
}
}
}
for(int i=2;i<n;i++){
if(!prime[i]) cnt++;
}
return cnt;
}
}