4Sum
问题简介:定n个整数和整数目标的数组nums,是否有元素a,b,c,d在nums中,使a+b+c+d=target?
举例:
给定数组 nums = [1, 0, -1, 0, -2, 2], 目标值 target = 0.
结果:
[
[-1, 0, 0, 1],
[-2, -1, 1, 2],
[-2, 0, 0, 2]
]
解法一:先将数组排序,通过三层循环,寻找是否符合四数之和的结果
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
Set<List<Integer>> res = new HashSet<>();
Arrays.sort(nums);
for(int i = 0; i <nums.length - 3;++i) {
for (int j = i + 1; j < nums.length - 2; ++j) {
if (j > i + 1 && nums[j] == nums[j - 1]) continue;
int left = j + 1, right = nums.length - 1;
while (left < right) {
int sum = nums[i] + nums[j] + nums[left] + nums[right];
if (sum == target) {
List<Integer> out = new ArrayList<>();
out.add(nums[i]);
out.add(nums[j]);
out.add(nums[left]);
out.add(nums[right]);
res.add(out);
++left; --right;
} else if (sum < target) ++left;
else --right;
}
}
}
return new ArrayList(res);
}
}
注:
1.contains方法使用场景
list/Set - contains()
Map - containsKey()/containsValue()
2.
Map的四种遍历 key-values
HashMap<String,String> map = new HashMap<>();
- 只获取values
for(String value : map.values()){} - 先获取Key的集合
for(String key : map.keySet()){
String value = map.get(key);} - Iterator迭代器
Iterator<Map.Entry<String, String>> iterator = map.entrySet().Iterator();
while(iterator.hasNext()){
Map.Entry<String, String> entry = iterator.next();
String key = entry.getKey();
String value= entry.getValue();}
- 常用的
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value= entry.getValue();
}
小白刷题之路,请多指教— — 要么大器晚成,要么石沉大海