349. Intersection of Two Arrays
来源:互联网 发布:wirelessmon mac版 编辑:程序博客网 时间:2024/06/05 07:50
1.
采用两个hashset 时间复杂度为O(n);6ms;
class Solution { public int[] intersection(int[] nums1, int[] nums2) { //use two hashset Set<Integer> set=new HashSet<>(); Set<Integer> interset=new HashSet<>(); for (int i=0;i<nums1.length;i++){ set.add(nums1[i]); } for (int i=0;i<nums2.length;i++){ if (set.contains(nums2[i])){ interset.add(nums2[i]); } } int[] result=new int[interset.size()]; int i=0; for(Integer num:interset){ result[i++]=num; } return result; }}
2.
先进行排序在比较相等之后加入到set中,并转为list;O(nlogn); 5ms;
Set<Integer> set=new HashSet<>(); Arrays.sort(nums1); Arrays.sort(nums2); int i=0,j=0; while(i<nums1.length&&j<nums2.length){ if (nums1[i]<nums2[j]) i++; else if (nums1[i]>nums2[j]) j++; else { set.add(nums1[i]); i++; j++; } } int[] result=new int[set.size()]; int k=0; for (Integer num:set){ result[k++]=num; } return result;
3.
排序一个list,再采用二分搜索判断相等加入到set中;O(nlogn); 9ms;
class Solution { public int[] intersection(int[] nums1, int[] nums2) { Set<Integer> set=new HashSet<>(); Arrays.sort(nums2); for(Integer num:nums1){ if (binarySearch(nums2,num)) set.add(num); } int[] result=new int[set.size()]; int i=0; for (Integer num:set){ result[i++]=num; } return result; } public boolean binarySearch(int[] nums, int target){ int low=0,high=nums.length-1; while (low<=high){ int mid=low+(high-low)/2; if (nums[mid]==target) return true; else if (nums[mid]>target) high=mid-1; else low=mid+1; } return false; }}
阅读全文
0 0
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays[][
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- 349. Intersection of Two Arrays
- android java中遇到的异常及报错如何解决?
- HihoCoder 1317 题解
- 通信协议——uart
- java jdk配置问题
- JAVA提高篇(25)--PrintWriter简介
- 349. Intersection of Two Arrays
- 【牛客】 操作系统 处理机的所有指令可以在()中执行。
- Java的三大框架
- Linux下解压命令大全
- HashMap全面分析及JDK8对HashMap的相关优化
- 为什么matplotlib显示opencv图像不正常
- 文件系统的挂载(NIS NFS Automounter)
- MySQL常用命令
- ACdream-1171 Matrix sum, 最大费用最大流