lintcode:两个数组的交
2016-07-07 09:56
253 查看
题目
返回两个数组的交
样例
nums1 =
解题
排序后,两指针找相等元素,注意要去除相同的元素
利用HashMap
将数组1的值唯一的保存在map中
根据map在去重
返回两个数组的交
样例
nums1 =
[1, 2, 2, 1], nums2 =
[2, 2], 返回
[2].
解题
排序后,两指针找相等元素,注意要去除相同的元素
public class Solution { /** * @param nums1 an integer array * @param nums2 an integer array * @return an integer array */ public int[] intersection(int[] nums1, int[] nums2) { // Write your code here Arrays.sort(nums1); Arrays.sort(nums2); ArrayList<Integer> A = new ArrayList<Integer>(); int i=0; int j=0; while(i<nums1.length && j<nums2.length ){ if(nums1[i] == nums2[j]){ A.add(nums1[i]); i++; j++; }else if(nums1[i] < nums2[j]){ i++; }else{ j++; } int tmpi = i; int tmpj = j; // 去重 while(i+1<nums1.length && nums1[i]==nums1[i+1]) i++; while(j+1<nums2.length && nums2[j]==nums2[j+1]) j++; // 没有重复,按照上面更新的i 和 j if(tmpi<nums1.length && tmpi ==i){ i= tmpi; } if(tmpj<nums2.length && tmpj ==j){ j = tmpj; } } int[] res = new int[A.size()]; for( i=0;i<A.size();i++){ res[i] = (int)A.get(i); } return res; } }
利用HashMap
将数组1的值唯一的保存在map中
根据map在去重
public class Solution { /** * @param nums1 an integer array * @param nums2 an integer array * @return an integer array */ public int[] intersection(int[] nums1, int[] nums2) { // Write your code here HashMap<Integer,Integer> map = new HashMap<Integer,Integer>(); for(int i =0;i<nums1.length;i++){ if(!map.containsKey(nums1[i])){ // 唯一映射 map.put(nums1[i],1); } } ArrayList<Integer> A = new ArrayList<Integer>(); for(int i=0;i<nums2.length;i++){ if(map.containsKey(nums2[i])){ // 相同元素 A.add(nums2[i]); map.remove(nums2[i]); // 去除相同元素 } } int[] res = new int[A.size()]; for(int i=0;i<A.size();i++){ // 保存到数组中 res[i] = A.get(i); } return res; } }
相关文章推荐
- 使用JAX-WS开发简单webservice
- java redis
- 分布式-远程部署的RMI
- Android文件监控FileObserver介绍
- Linux上安装JDK环境变量配置
- CISCO路由器配置防止DDOS攻击
- phpCMS 使用总结
- Android APK版本升级设计
- 1027. Colors in Mars (20)
- 危机十足站长的生命觉悟:拼命也得每天挤一滴墨水!
- Android中的dispatchTouchEvent()、onInterceptTouchEvent()和onTouchEvent()
- jQuery EasyUI使用教程之加载父/子节点到树中
- STL中的RB-tree
- 妨碍企业推广的不是SEO技术,而是自身思维
- EXCEL科学计数法转为文本格式
- Entity Framework Tutorial Basics(10):Entity Lifecycle
- IPv6 Neighbor Discovery (ND) and Multicast Listener Discovery (MLD) Challenges
- shell编程之if判断
- CocoaPods 安装不成功
- container在运行的时候重启 docker 服务, 可能会导致 container无法启动