LeetCode Task04
LeetCode 1 两数之和
- 题目描述
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍
- 代码实现
public int[] twoSum(int[] nums, int target) {
//1 数组排序
Map<Integer,Integer> hashMap = new HashMap<>();
for(int i=0;i < nums.length;i++) {
hashMap.put(i,nums[i]);
}
//根据value排序
hashMap.entrySet().stream().sorted(Map.Entry.comparingByValue());
//log.info(hashMap.toString());
/**
* 根据key排序
* hashMap.entrySet().stream().sorted(Map.Entry.<Integer, Integer>comparingByKey());
* hashMap.entrySet().stream().sorted(Map.Entry.comparingByValue()).collect(Collectors.toSet());
*/
//2 寻找
int[] res = new int[2];
Set<Map.Entry<Integer, Integer>> entries = hashMap.entrySet();
for(Map.Entry<Integer,Integer> entry1 :entries) {
entries.remove(entry1);
for(Map.Entry<Integer,Integer> entry2: entries){
int tg = entry1.getValue() + entry2.getValue();
}
}
return null;
}
LeetCode 15. 三数之和
- 题目描述
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有满足条件且不重复的三元组。
注意:答案中不可以包含重复的三元组。
这里是引用给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[ [-1, 0, 1], [-1, -1, 2] ]
- 代码实现
LeetCode 18. 四数之和
-
题目描述
给出一个整形数组,寻找其中的所有不同的四元组(a,b,c,d),使得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]]
- 代码实现
LeetCode 454. 四数之和2
- 题目描述
给定四个包含整数的数组列表 A , B , C , D ,计算有多少个元组 (i, j, k, l) ,使得 A[i] + B[j] + C[k] + D[l] = 0。
为了使问题简单化,所有的 A, B, C, D 具有相同的长度 N,且 0 ≤ N ≤ 500 。所有整数的范围在 -228 到 228 - 1 之间,最终结果不会超过 231 - 1 。
这里是
输入:
A = [ 1, 2]
B = [-2,-1]
C = [-1, 2]
D = [ 0, 2]
输出:
2
- 代码实现
LeetCode 49. 四数之和
- 题目描述
给出一个整形数组,寻找其中的所有不同的四元组(a,b,c,d),使得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]]
- 代码实现
LeetCode 49. 字母异位词分组
- 题目描述
给出一个字符串数组,将其中所有可以通过颠倒字符顺序产生相同结果的单词进行分组。
这里是引用给定数组 nums = [-1, 0, 1, 2, -1, -4],
满足要求的三元组集合为:
[ [-1, 0, 1], [-1, -1, 2] ]
- 代码实现
public List<List<Integer>> threeSum(int[] nums) {
if (nums == null || nums.length <= 2) {
return Collections.emptyList();
}
// sort
Arrays.sort(nums);
List<List<Integer>> list = new LinkedList<>();
// first loop
for (int i = 0; i < nums.length - 2; i++) {
if (nums[i] > 0) break;
if (i > 0 && nums[i] == nums[i - 1]) continue;
int right = nums.length - 1;
// second loop to judge sum of three numbers
for (int left = i + 1; left < nums.length; left++) {
if (left > i + 1 && nums[left] == nums[left - 1]) continue;
while (left < right && nums[i] + nums[left] + nums[right] > 0) {
right--;
}
if (left == right) break;
if (nums[i] + nums[left] + nums[right] == 0) {
list.add(Arrays.asList(nums[i], nums[left], nums[right]));
}
}
}
return list;
}