LeetCode Intersetion of two array
来源:互联网 发布:李涛疯狂淘宝 传销 编辑:程序博客网 时间:2024/06/05 12:41
description:
Given two arrays, write a function to compute their intersection.Example:Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].Note:Each element in the result must be unique.The result can be in any order.
解题思路: 使用排序算法然后再进行处理,注意当比较两个数组相等的时候,要排除相同的数据的情况,也就是一个选代表的过程,当两个数字是相等时也要注意同时将数组的下表加一。
public class Solution { public int[] intersection(int[] nums1, int[] nums2) { if (nums1 == null || nums2 == null) { return null; } Arrays.sort(nums1); Arrays.sort(nums2); int[] arr = new int[Math.min(nums1.length, nums2.length)]; int i = 0, j = 0, index = 0; while (i < nums1.length && j < nums2.length) { if (nums1[i] == nums2[j]) { if (index == 0 || arr[index - 1] != nums1[i]) { arr[index++] = nums1[i]; } j++; i++; } else if (nums1[i] > nums2[j]) { j++; } else { i++; } } int[] result = new int[index]; for (int k = 0; k < index; k++) { result[k] = arr[k]; } return result; }}
当然,这道题目也能够使用hashmap的方式进行求解,当所要的数据存在于map中的时候,数组添加这个数,反复这一过程直到求解出所用的数据。
0 0
- LeetCode Intersetion of two array
- LeetCode 4: Median Of Two Sorted Array
- Leetcode - Median of Two Sorted Array
- Median of Two Sorted Array---LeetCode
- [leetcode] #4 Median of Two Sorted Array
- LeetCode:Median of two sorted array
- Leetcode--Median of Two Sorted Array
- [Leetcode]Median of two sorted array
- Leetcode-349-Intersection of Two Array
- [LeetCode]Median of Two Sorted Array
- Median of Two Sorted Array leetcode java
- LeetCode 349. Intersection of Two Array
- LeetCode 350. Intersection of Two Array
- Median of Two Sorted Array leetcode java
- LeetCode 350. Intersection of Two Array II 解题报告
- 【LeetCode-421】Maximum XOR of Two Numbers in an Array
- [leetcode]421. Maximum XOR of Two Numbers in an Array
- LeetCode #421: Maximum XOR of Two Numbers in an Array
- 欢迎使用CSDN-markdown编辑器
- 熄灯之后的学习——再读《MySQL必知必会》(6)|| 数据过滤
- gradle android 目录结构
- B. Find The Bone
- macbook 配置 Maven
- LeetCode Intersetion of two array
- C#FTP帮助 类
- 依赖传递
- gradle 打印依赖树
- gradle 查看库本地存储地址
- android基础知识---语言切换
- gradle 包装器
- COGS 728. [网络流24题] 最小路径覆盖问题
- for 对vector类型进行循环输出