-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01.twoSum
More file actions
31 lines (28 loc) · 720 Bytes
/
01.twoSum
File metadata and controls
31 lines (28 loc) · 720 Bytes
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
// Better in O(nlogn)
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map=new HashMap<>();
for(int i=0;i<nums.length;i++){
int diff=target-nums[i];
if(map.containsKey(diff)){
return new int[] {map.get(diff), i};
}
map.put(nums[i],i);
}
return new int[] {-1,-1};
}
}
// Brute in O(n^2)
class Solution {
public int[] twoSum(int[] nums, int target) {
int n=nums.length;
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
if(nums[i]+nums[j]==target){
return new int[] {i,j};
}
}
}
return new int[] {};
}
}