350. Intersection of Two Arrays II
来源:互联网 发布:做一名网络星探的诀窍 编辑:程序博客网 时间:2024/05/21 18:33
题目:https://leetcode.com/problems/intersection-of-two-arrays-ii/
代码:
public class Solution { public int[] intersect(int[] nums1, int[] nums2) { int[] flag = new int[nums2.length]; ArrayList<Integer> m = new ArrayList<Integer>(); for(int i=0;i<nums1.length;i++) { for(int j=0;j<nums2.length;j++) { if(flag[j]==1) continue; if(nums1[i]==nums2[j]) { m.add(nums1[i]); flag[j] = 1; break; } } } int[] a = new int[m.size()]; int count = 0; for( int i : m ) { a[count] = i; count++; } return a; }}我的方法是设置标记,不过还是要遍历====================================dicuss里面有一个两点的想法,我试着实现以下先对数组排序,而后用两点移动判断能减少次数public class Solution { public int[] intersect(int[] nums1, int[] nums2) { if(nums1.length==0||nums2.length==0) return new int[0]; Arrays.sort(nums1); Arrays.sort(nums2); int count=0; int[] m = new int[nums1.length>nums2.length?nums1.length:nums2.length]; for(int p1=0,p2=0;p1<nums1.length&&p2<nums2.length;) { if(nums1[p1]==nums2[p2]) { m[count] = nums1[p1]; count++; p1++; p2++; } else if(nums1[p1]>nums2[p2]) p2++; else p1++; } int[] a = new int[count]; for(int i =0;i<count;i++) { a[i] = m[i]; } return a; }}4ms
0 0
- 350. Intersection of Two Arrays II
- LeetCode 350. Intersection of Two Arrays II
- leetcode.350. Intersection of Two Arrays II
- 350. Intersection of Two Arrays II【E】
- 350. Intersection of Two Arrays II
- [leetcode] 350. Intersection of Two Arrays II
- Leetcode 350. Intersection of Two Arrays II
- leetcode 350. Intersection of Two Arrays II
- 350. Intersection of Two Arrays II
- 350. Intersection of Two Arrays II
- Leetcode 350. Intersection of Two Arrays II
- [leetcode] 350. Intersection of Two Arrays II
- leetcode 350. Intersection of Two Arrays II
- 350. Intersection of Two Arrays II
- 350. Intersection of Two Arrays II
- 【leetcode】350. Intersection of Two Arrays II
- 350. Intersection of Two Arrays II
- 350. Intersection of Two Arrays II
- 169. Majority Element
- 使用RxJava和RxAndroid封装RxBus,实现EventBus功能
- java 中wait和notify 线程等待和线程唤醒的使用方式 需要借助synchronized
- 217. Contains Duplicate
- LeetCode-29.Divide Two Integers
- 350. Intersection of Two Arrays II
- 机器学习整理笔记——k-近邻算法
- 关于EventBus的基本应用(基于v3.0)
- Java注解在Android中使用
- 206. Reverse Linked List
- win10下完全卸载+重装MySQL教程
- 数据库编程细节问题 --1. insert与where问题
- 【电影】X战警天启HDTC版免费观看英文中字字幕
- 235. Lowest Common Ancestor of a Binary Search Tree