未完待续…
题目源于: https://leetcode-cn.com
1) 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
- 给定 nums = [2, 7, 11, 15], target = 9
- 因为 nums[0] + nums[1] = 2 + 7 = 9
- 所以返回 [0, 1]
class Demo {
public static void main(String[] args) {
int[] nums = {2, 8, 7, 15};
int target = 9;
int[] ints = sum(nums, target);
System.out.println(Arrays.toString(ints));
}
public static int[] sum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(target - nums[i])) {
return new int[]{map.get(target - nums[i]), i};
}
map.put(nums[i], i);
}
throw new RuntimeException("该数组中未匹配到,两数之和 等于 target ");
}
}
2) 需求: 请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。
import java.util.Arrays;
public class FindMedianSorted {
public static void main(String[] args) {
int[] nums1 = {1, 2, 3};
int[] nums2 = {4, 5, 6};
double num = findMedianSortedArrays(nums1, nums2);
System.out.println("中位数是: " + num);
}
private static double findMedianSortedArrays(int[] nums1, int[] nums2) {
int[] nums3 = new int[nums1.length + nums2.length];
System.arraycopy(nums1, 0, nums3, 0, nums1.length);
System.arraycopy(nums2, 0, nums3, nums1.length, nums2.length);
Arrays.sort(nums3);
if (nums3.length % 2 > 0) {
return nums3[(nums3.length / 2)];
} else {
return (double)(nums3[(nums3.length / 2)] + nums3[(nums3.length / 2) - 1]) / 2;
}
}
}