LintCode做题记录-两数组的交 II
2016-08-06 12:44
316 查看
LintCode做题记录-两数组的交 II
题目要求:
计算两个数组的交
每个元素出现次数得和在数组里一样
答案可以以任意顺序给出
示例:
nums1 = [1, 2, 2, 1], nums2 = [2, 2], 返回 [2, 2].
试过两种方法,都贴一下
常规办法(83%的时候超时)
public int[] getIntersection(int[] nums1, int[] nums2) { List<Integer> list1 = new ArrayList<>(); List<Integer> list2 = new ArrayList<>(); List<Integer> result = new ArrayList<>(); if (nums1.length > nums2.length) { for (int i = 0; i < nums1.length; i++) { list1.add(nums1[i]); } for (int i = 0; i < nums2.length; i++) { list2.add(nums2[i]); } } else { for (int i = 0; i < nums1.length; i++) { list2.add(nums1[i]); } for (int i = 0; i < nums2.length; i++) { list1.add(nums2[i]); } } for (int i = 0; i < list1.size(); i++) { int n = list1.get(i); if (list2.contains(n)) { list2.remove(list2.indexOf(n)); result.add(n); } } int[] nums = new int[result.size()]; for (int i = 0; i < result.size(); i++) { nums[i] = result.get(i); } return nums; }
完全通过的方法
public int[] getIntersection(int[] nums1, int[] nums2) { if (nums1.length == 0 || nums2.length == 0) { return new int[]{}; } Arrays.sort(nums1); Arrays.sort(nums2); List<Integer> list = new ArrayList<>(); int index1 = 0; int index2 = 0; while (index1 < nums1.length && index2 < nums2.length) { if (nums1[index1] == nums2[index2]) { list.add(nums1[index1]); index1++; index2++; } else { if (nums1[index1] < nums2[index2]) { index1++; } else { index2++; } } } int[] nums = new int[list.size()]; for (int j = 0; j < list.size(); j++) { nums[j] = list.get(j); } return nums; }
相关文章推荐
- lintcode之 合并排序数组 II
- lintcode&九章算法——101. 删除有序数组里的重复元素 II ? 待解决
- lintcode:两数组的交 II
- LintCode Remove Duplicates from Sorted Array II 删除排序数组中的重复数字 II
- lintcode 两数组的交II
- LintCode 6.合并排序数组 II
- LintCode Merge Sorted ArrayII 合并排序数组 II
- lintcode 中等题:search in rotated sorted arrayII 搜索旋转排序数组II
- lintcode -- 最大子数组II
- lintcode--42. 最大子数组 II
- LintCode Python 101. 删除排序数组中的重复数字 II
- Lintcode6——合并排序数组 II
- lintcode 42 最大子数组 II 解析
- LintCode:两数组的交 II
- LintCode_63_搜索旋转排序数组 II
- LintCode:搜索旋转排序数组 II
- lintcode-搜索二维矩阵II-38
- lintcode:Longest Increasing Continuous subsequence II
- lintcode-子数组之和-138
- LintCode Majority Number II / III