算法汇总
以下是所有算法汇总,包括GitHub源码地址链接:力扣算法练习汇总(持续更新…)
题目
代码
1.双hashSet
set遍历的方式(这是基础很重要)
1.迭代遍历:
Set<String> set = new HashSet<String>();
Iterator<String> it = set.iterator();
while (it.hasNext()) {undefined
String str = it.next();
System.out.println(str);
}
2.for循环遍历:
for (String str : set) {undefined
System.out.println(str);
}
代码
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {
return new int[0];
}
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;
}
}
时间和空间复杂度
2.暴力法
思路
代码
class Solution {
// 暴力法
public int[] intersection(int[] nums1, int[] nums2) {
// 存放交集元素
HashSet<Integer> resultSet = new HashSet<>();
for(int i = 0; i < nums1.length; i++){
for(int j = 0; j < nums2.length; j++){
if(nums1[i] == nums2[j]){
resultSet.add(nums1[i]);
}
}
}
// 结果数组
int[] resultArr = new int[resultSet.size()];
int index = 0;
for(Integer i : resultSet){
resultArr[index] = i;
index++;
}
return resultArr;
}
}
时间和空间复杂度
- 时间复杂度是$O(n^2)