Intersection of Two Arrays II
来源:互联网 发布:淘宝退款申请客服介入 编辑:程序博客网 时间:2024/05/04 02:13
这道题的非排序做法值得自己再好好看看,尤其是while循环中的三个条件
非排序
public class Solution { public int[] intersect(int[] nums1, int[] nums2) {int [] result = new int[0];if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {return result;} List<Integer/*value*/> list = new LinkedList<>();Map<Integer/*value*/,Integer/*number*/> map = new HashMap<>();for (int i: nums1) {if (map.containsKey(i)){map.put(i, map.get(i) + 1);} else {map.put(i, 1);}}for (int i: nums2) {if (map.containsKey(i) && map.get(i) > 0){list.add(i);map.put(i, map.get(i) - 1);}}result = new int[list.size()];int i = 0;for (int k: list) {result[i++] = k;}return result; }}
排序的方法
public class Solution { public int[] intersect(int[] nums1, int[] nums2) {int [] temp = new int[0]; if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) { return temp; } Arrays.sort(nums1); Arrays.sort(nums2); int i = 0, j = 0, k = 0; temp = new int[nums1.length]; while (i < nums1.length && j < nums2.length) { //if (nums1[i] != nums2[j]) { if (nums1[i] < nums2[j]) { i++; } else if (nums1[i] == nums2[j]) { temp[k++] = nums1[i]; i++; j++; } else { j++; } } int[] result = new int[k]; for (int m = 0; m < k; m++) { result[m] = temp[m]; } return result; }}
0 0
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays II
- Intersection of Two Arrays&Intersection of Two Arrays II
- [LeetCode] Intersection of Two Arrays II
- 350. Intersection of Two Arrays II
- LeetCode Intersection of Two Arrays II
- Intersection of Two Arrays
- 练习4-1 编写函数strrindex(s,t),它返回字符串t在s中最右边出现的位置。如果s中不包含t,则返回-1
- 最长递增自序列 python
- 树莓派 centos7 命令行播放音乐
- 统计学 分布篇 - Binomial Distribution(二项分布)
- Intersection of Two Arrays II
- 大家好
- mysql 查询重复次数最多/最少的几条记录
- std::map更新数值前是否需要初始化
- 《笑话大全》APP代码详解1
- Panda3D学习之路(二)
- 直接运行Python程序
- object references an unsaved transient instance - save the transient instance before flushing: org.t
- leecode_241 Different Ways to Add Parentheses