Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 1ea1960

Browse files
committed
Modified 2 solutions
1 parent eb32d4c commit 1ea1960

File tree

2 files changed

+26
-40
lines changed

2 files changed

+26
-40
lines changed

Easy/Binary Search.java

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,17 @@
11
class Solution {
22
public int search(int[] nums, int target) {
3-
return binarySearchImpl(nums, 0, nums.length - 1, target);
4-
}
5-
6-
private int binarySearchImpl(int[] nums, int start, int end, int target) {
7-
while (start <= end) {
8-
int mid = (start + end) / 2;
3+
int left = 0;
4+
int right = nums.length - 1;
5+
while (left <= right) {
6+
int mid = (left + right) / 2;
97
if (nums[mid] == target) {
108
return mid;
119
}
1210
else if (nums[mid] > target) {
13-
end = mid - 1;
11+
right = mid - 1;
1412
}
1513
else {
16-
start = mid + 1;
14+
left = mid + 1;
1715
}
1816
}
1917
return -1;

Easy/Two Sum III - Data Structure Design.java

Lines changed: 20 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,27 @@
11
class TwoSum {
22

3-
/** Initialize your data structure here. */
4-
List<Integer> list;
5-
Map<Integer, Integer> map;
6-
public TwoSum() {
7-
list = new ArrayList<>();
8-
map = new HashMap<>();
9-
}
10-
11-
/** Add the number to an internal data structure.. */
12-
public void add(int number) {
13-
if (map.containsKey(number)) {
14-
map.put(number, map.get(number) + 1);
15-
}
16-
else {
17-
map.put(number, 1);
18-
list.add(number);
19-
}
20-
}
21-
22-
/** Find if there exists any pair of numbers which sum is equal to the value. */
23-
public boolean find(int value) {
24-
for (int num : list) {
25-
int diff = value - num;
26-
if (diff != num && map.containsKey(diff)) {
27-
return true;
28-
}
29-
30-
if (diff == num && map.get(diff) > 1) {
31-
return true;
32-
}
3+
/** Initialize your data structure here. */
4+
Map<Integer, Integer> map;
5+
public TwoSum() {
6+
map = new HashMap<>();
7+
}
8+
9+
/** Add the number to an internal data structure.. */
10+
public void add(int number) {
11+
map.put(number, map.getOrDefault(number, 0) + 1);
12+
}
13+
14+
/** Find if there exists any pair of numbers which sum is equal to the value. */
15+
public boolean find(int value) {
16+
for (Integer key : map.keySet()) {
17+
if (map.containsKey(value - key)) {
18+
if (value - key != key || (value - key == key && map.get(key) > 1)) {
19+
return true;
3320
}
34-
35-
return false;
21+
}
3622
}
23+
return false;
24+
}
3725
}
3826

3927
/**

0 commit comments

Comments
 (0)