Skip to content

Commit 49517bd

Browse files
committed
Java solution 001/004
1 parent dfc02bc commit 49517bd

File tree

2 files changed

+79
-0
lines changed

2 files changed

+79
-0
lines changed

java/_001TwoSum.java

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import java.util.HashMap;
2+
import java.util.Map;
3+
4+
/**
5+
* Given an array of integers, return indices of the two numbers such that they add up to a specific target.
6+
* You may assume that each input would have exactly one solution, and you may not use the same element twice.
7+
* <p>
8+
* Example:
9+
* Given nums = [2, 7, 11, 15], target = 9,
10+
* Because nums[0] + nums[1] = 2 + 7 = 9,
11+
* return [0, 1].
12+
* <p>
13+
* Created by drfish on 04/05/2017.
14+
*/
15+
public class _001TwoSum {
16+
public int[] twoSum(int[] nums, int target) {
17+
int[] result = new int[2];
18+
Map<Integer, Integer> map = new HashMap<>();
19+
for (int i = 0; i < nums.length; i++) {
20+
if (map.containsKey(target - nums[i])) {
21+
result[0] = map.get(target - nums[i]);
22+
result[1] = i;
23+
return result;
24+
}
25+
map.put(nums[i], i);
26+
}
27+
return result;
28+
}
29+
}

java/_004MedianOfTwoSortedArrays.java

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import com.sun.org.apache.regexp.internal.recompile;
2+
3+
/**
4+
* There are two sorted arrays nums1 and nums2 of size m and n respectively.
5+
* Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
6+
* <p>
7+
* Example 1:
8+
* nums1 = [1, 3]
9+
* nums2 = [2]
10+
* The median is 2.0
11+
* <p>
12+
* Example 2:
13+
* nums1 = [1, 2]
14+
* nums2 = [3, 4]
15+
* The median is (2 + 3)/2 = 2.5
16+
* <p>
17+
* Created by drfish on 04/05/2017.
18+
*/
19+
public class _004MedianOfTwoSortedArrays {
20+
public double findMedianSortedArrays(int[] nums1, int[] nums2) {
21+
int k1 = (nums1.length + nums2.length + 1) / 2;
22+
int k2 = (nums1.length + nums2.length + 2) / 2;
23+
return (findK(nums1, 0, nums2, 0, k1) + findK(nums1, 0, nums2, 0, k2)) / 2.0;
24+
}
25+
26+
private double findK(int[] nums1, int start1, int[] nums2, int start2, int k) {
27+
if (start1 >= nums1.length) {
28+
return nums2[start2 + k - 1];
29+
}
30+
if (start2 >= nums2.length) {
31+
return nums1[start1 + k - 1];
32+
}
33+
if (k == 1) {
34+
return Math.min(nums1[start1], nums2[start2]);
35+
}
36+
int mid1 = Integer.MAX_VALUE;
37+
int mid2 = Integer.MAX_VALUE;
38+
if (start1 + k / 2 - 1 < nums1.length) {
39+
mid1 = nums1[start1 + k / 2 - 1];
40+
}
41+
if (start2 + k / 2 - 1 < nums2.length) {
42+
mid2 = nums2[start2 + k / 2 - 1];
43+
}
44+
if (mid1 < mid2) {
45+
return findK(nums1, start1 + k / 2, nums2, start2, k - k / 2);
46+
} else {
47+
return findK(nums1, start1, nums2, start2 + k / 2, k - k / 2);
48+
}
49+
}
50+
}

0 commit comments

Comments
 (0)