标签:leecode349 交集 int resSet 数组 new nums1 nums2
本题做法是利用Hash表去除重复元素,然后用HashSet放重复元素,用一个数组输出。
我的本来思想是用两个容量为10数组分别标记两个数组存在的元素,存在则相应位置+1,最后把元素重复的位置全部变为1,即把不等于1且不等于0的元素变为1。然后将两个数组比较,将相等且为1的索引输出。但是问题是输出的数组不是动态的,在重复元素后会输出0元素,看了看答案感觉思想是对的,但是需要用HashSet来做。
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
int[] res = new int[10];
Set<Integer> resSet = new HashSet<>();
for (int i =0; i < nums1.length; i ++) {
res[nums1[i]] ++;
if (res[nums1[i]] != 0 && res[nums1[i]] != 1) {
res[nums1[i]] = 1;
}
}
for (int i : nums2) {
if (nums1[i] == 1) {
resSet.add(i);
}
}
for (int j = 0; j < nums2.length; j ++) {
tem[nums2[j]] ++;
if (tem[nums2[j]] != 0 && tem[nums2[j]] != 1) {
tem[nums2[j]] = 1;
}
}
int[] ress = new int[resSet.size()];
int index = 0;
//将结果几何转为数组
for (int i : resSet) {
ress[index++] = i;
}
return ress
}
标准做法:
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<>();
Set<Integer> resSet = new HashSet<>();
//遍历数组1
for (int i : nums1) {
set1.add(i);
}
//遍历数组2的过程中判断哈希表中是否存在该元素
for (int i : nums2) {
if (set1.contains(i)) {
resSet.add(i);
}
}
int[] resArr = new int[resSet.size()];
int index = 0;
//将结果几何转为数组
for (int i : resSet) {
resArr[index++] = i;
}
return resArr;
}
}
标签:leecode349,交集,int,resSet,数组,new,nums1,nums2 来源: https://blog.csdn.net/maocaicai/article/details/122390810
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。