Repository navigation
Expand file tree
/
Copy pathTwoSum.java
More file actions
153 lines (122 loc) · 2.53 KB
/
Copy pathTwoSum.java
File metadata and controls
153 lines (122 loc) · 2.53 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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
package LeetCode;
import java.util.*;
public class TwoSum {
public static void main(String args[]) throws Exception
{
int[] arr = new int[]{0, 4, 3, 0};
int[] indices = twoSum(arr, 0);
System.out.println(indices[0] + " " + indices[1]);
}
public static int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> dict = new HashMap<Integer, Integer>();
int[] arr = new int[2];
for (int i=0; i<nums.length; i++)
{
if (dict.containsKey(nums[i]))
{
int index1 = dict.get(nums[i]);
int index2 = i+1;
arr[0] = index1;
arr[1] = index2;
}
else
{
dict.put(target - nums[i], i+1);
}
}
return arr;
}
/*
int[] copy = new int[nums.length];
wrapper[] wrapp = new wrapper[nums.length];
for (int i=0; i<nums.length; i++)
{
wrapper wrap = new wrapper(i, nums[i]);
wrapp[i] = wrap;
}
Arrays.sort(wrapp, new WrapperComparator());
int low = 0;
int high = nums.length - 1;
int[] arr = new int[2];
while (low < high)
{
if ((wrapp[low].value + wrapp[high].value) > target)
{
high--;
}
else if ((wrapp[low].value + wrapp[high].value) < target)
{
low++;
}
else
{
//System.out.print(low + " " + high);
// find low in original
/*int temp = 0;
for( int i=0; i<nums.length; i++)
{
if (nums[i] == copy[low])
{
temp = i;
break;
}
}
arr[0] = temp + 1;
temp = 0;
for( int i=0; i<nums.length; i++)
{
if (nums[i] == copy[high])
{
temp = i;
break;
}
}
arr[1] = temp + 1;
arr[0] = wrapp[low].index + 1;
arr[1] = wrapp[high].index + 1;
int min = Math.min(arr[0], arr[1]);
int max = Math.max(arr[0], arr[1]);
arr[0] = min;
arr[1] = max;
return arr;
}
}
return arr;
} */
}
class WrapperComparator implements Comparator<wrapper>
{
public int compare(wrapper h1, wrapper h2)
{
int cmp = 0;
if (h1.value < h2.value)
{
return -1;
}
if (h1.value > h2.value)
{
return 1;
}
else
{
if (h1.index < h2.index)
{
return -1;
}
if (h1.index > h2.index)
{
return 1;
}
}
return cmp;
}
}
class wrapper {
public int value;
public int index;
public wrapper(int index, int value)
{
this.index = index;
this.value = value;
}
}