-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayProblems.java
More file actions
81 lines (72 loc) · 1.74 KB
/
ArrayProblems.java
File metadata and controls
81 lines (72 loc) · 1.74 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
import java.util.Random;
import java.util.Hashtable;
import java.util.List;
import java.util.ArrayList;
import java.util.Set;
public class ArrayProblems{
public static void main(String arg[]){
int N = 55;
int A[] = new int[N];
Random r = new Random();
for(int i = 0; i < A.length; i++){
int v = r.nextInt(30);
A[i] = v > 10? v-30:v;
//A[i] = v;
System.out.print(A[i] + ", ");
}
int k = r.nextInt(100);
System.out.println();
//sumK(A,k);
ZeroSum(A);
}
public static void sumK(int A[], int k){
int start = 0;
int currentSum = 0;
int counter = 0;
for(int i = 0; i < A.length; i++){
currentSum += A[i];
if(currentSum == k ){
counter++;
for(int j = start; j <= i; j++){
System.out.print(A[j] + ", ");
}
System.out.println(" = " + k);
currentSum -=A[start++];
}
while( currentSum > k){
currentSum -= A[start++];
}
}
if(counter == 0) {
System.out.println("cannot find Sum K = "+ k);
}
}
public static void ZeroSum(int A[]){
int currentKey = 0;
Hashtable<Integer,List<Integer>> table = new Hashtable<Integer,List<Integer>>();
for(int i = 0; i < A.length; i++){
currentKey += A[i];
if(table.containsKey(currentKey)){
table.get(currentKey).add(i);
}else{
List<Integer> list = new ArrayList<Integer>();
list.add(i);
table.put(currentKey,list);
}
}
Set<Integer> keys = table.keySet();
for(Integer key: keys){
List<Integer> list = table.get(key);
if(list.size() > 1){
for(int i = 0; i < list.size() -1; i++){
for(int j= i+1; j < list.size(); j++){
for(int k = list.get(i) + 1; k <= list.get(j); k++){
System.out.print(A[k] + " + ");
}
System.out.println(" = 0");
}
}
}
}
}
}