当前位置:网站首页>Hash - 18. Sum of four numbers
Hash - 18. Sum of four numbers
2022-07-24 11:29:00 【Xiao Zhao, who is working hard for millions of annual salary】
1 Title Description
- Sum of four numbers
Here you are n An array of integers nums , And a target value target . Please find and return the quads that meet all the following conditions and are not repeated [nums[a], nums[b], nums[c], nums[d]] ( If two Quad elements correspond to each other , It is considered that two quads repeat ):
0 <= a, b, c, d < n
a、b、c and d Different from each other
nums[a] + nums[b] + nums[c] + nums[d] == target
You can press In any order Return to the answer .
2 Title Example
Example 1:
Input :nums = [1,0,-1,0,-2,2], target = 0
Output :[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
Example 2:
Input :nums = [2,2,2,2,2], target = 8
Output :[[2,2,2,2]]
3 Topic tips
1 <= nums.length <= 200
-109 <= nums[i] <= 109
-109 <= target <= 109
4 Ideas
Sort + Double pointer
The simplest way is to enumerate all quaternions in a quadruple loop , Then the hash table is used for de duplication , Get the final answer that does not contain duplicate quads . Let's say the length of the array is n, In this method , The time complexity of enumeration is O(n4), The time complexity and space complexity of de duplication operation are also very high , So we need to change — Ideas . To avoid enumerating to duplicate quads , You need to ensure that the elements enumerated in each loop are not less than the elements enumerated in the previous loop , And the same element cannot be enumerated multiple times in the same loop .
In order to achieve the above requirements , You can sort arrays , And follow the following two points during the cycle :
- Every time — The subscript enumerated by a loop must be greater than the upper — Iterate through the index of the enumeration ;
- Same as — Re cycling , If the current element is the same as the previous element , Then skip the current element .
Use the above method , You can avoid enumerating to duplicate quads , But because the quadruple cycle is still used , The time complexity is still o(n4). Notice that the array has been sorted , Therefore, the double pointer method can be used to remove a double loop .
Use a double loop to enumerate the first two numbers , Then, after the double loop enumeration of the number, use the double pointer to enumerate the remaining two numbers . Suppose that the first two numbers enumerated by the double loop are in the subscript i and j, among i<j. At the beginning , The left and right pointers point to the subscript j+1 And subscripts n―1. Calculate the sum of four numbers at a time , And do the following :
- If sum equals target, Then add the four numbers enumerated to the answer , Then move the left pointer to the right until a different number is encountered , Move the right pointer to the left until a different number is encountered ;
- If and less than target, Move the left pointer one bit to the right ;
- If and are greater than target, Move the right pointer one bit to the left .
The time complexity of enumerating the remaining two numbers with double pointers is O(n), So the total time complexity is o(n3), lower than O(n’).
Concrete implementation , You can also perform some pruning operations :
- After determining the first number , If nums[i]+ nums[i+1]+nums[i+2]+ nums[i+3] > target, Explain the remaining three numbers, no matter what value they take , The sum of four numbers must be greater than target, So quit the — Recirculation ;
- After determining the first number , If nums[i] + nums[n — 3]+nums[n —2] + nums[n ―1]<target, Explain the remaining three numbers, no matter what value they take , The sum of four numbers must be less than target, So the first cycle goes directly to the next round , enumeration nums[i+1];
- After determining the first two numbers , If nums[ department + nums[ij]+ numsl[j+1]+ nums[j+2] > target, Explain the remaining two numbers at this time, no matter what value they take , The sum of four numbers must be greater than target, So exit the second cycle ;
- After determining the first two numbers , If nums[i]+ nums[j]+nums[n — 2]+nums[n ― 1]<target, Explain the remaining two numbers at this time, no matter what value they take , The sum of four numbers must be less than target, So the second cycle goes directly to the next round , enumeration nums[j+1].
5 My answer
class Solution {
public List<List<Integer>> fourSum(int[] nums, int target) {
List<List<Integer>> quadruplets = new ArrayList<List<Integer>>();
if (nums == null || nums.length < 4) {
return quadruplets;
}
Arrays.sort(nums);
int length = nums.length;
for (int i = 0; i < length - 3; i++) {
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
if ((long) nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target) {
break;
}
if ((long) nums[i] + nums[length - 3] + nums[length - 2] + nums[length - 1] < target) {
continue;
}
for (int j = i + 1; j < length - 2; j++) {
if (j > i + 1 && nums[j] == nums[j - 1]) {
continue;
}
if ((long) nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target) {
break;
}
if ((long) nums[i] + nums[j] + nums[length - 2] + nums[length - 1] < target) {
continue;
}
int left = j + 1, right = length - 1;
while (left < right) {
int sum = nums[i] + nums[j] + nums[left] + nums[right];
if (sum == target) {
quadruplets.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
while (left < right && nums[left] == nums[left + 1]) {
left++;
}
left++;
while (left < right && nums[right] == nums[right - 1]) {
right--;
}
right--;
} else if (sum < target) {
left++;
} else {
right--;
}
}
}
}
return quadruplets;
}
}
边栏推荐
- 如何从功能测试到自动化测试?
- 08 [AIO programming]
- 【Golang】golang实现简单memcache
- 链表——142. 环形链表 II
- JMeter if controller
- CSDN会员的魅力何在?我要他有什么用?
- 【Golang】golang实现发送微信服务号模板消息
- The number of digits of power and factorial
- Pytorch learning -- using gradient descent method to realize univariate linear regression
- About [software testing - interview skills and precautions for automated testing] - talk freely
猜你喜欢

Only "a little bit", why do developers look up to you?

2022, the average salary of the soft tester, after reading it, I was instantly cool

Introduction to Devops and common Devops tools
![[markdown grammar advanced] make your blog more exciting (IV: set font style and color comparison table)](/img/a5/c92e0404c6a970a62595bc7a3b68cd.gif)
[markdown grammar advanced] make your blog more exciting (IV: set font style and color comparison table)

Types and history of bugs in it circle

tcp 服务端接收数据处理思路梳理,以及select: Invalid argument报错 笔记

CSDN会员的魅力何在?我要他有什么用?

Blue Bridge Cup provincial match training camp - Calculation of date

Pytorch learning -- using gradient descent method to realize univariate linear regression

Lanqiao cup provincial training camp - stack and recursion
随机推荐
E2PROM read / write (xiicps) on PS side of zcu102 board
Ask n! How many zeros are there behind
Best practice | using Tencent cloud AI character recognition to realize enterprise qualification certificate recognition
什么是云原生,云原生技术为什么这么火?
08【AIO编程】
【Golang】golang实现发送微信服务号模板消息
Introduction to Devops and common Devops tools
Research on parameter setting of MATLAB FFT
简单使用 MySQL 索引
【Golang】golang中map元素的删除和清空
[golang] golang implements the post request to send form type data function
[markdown grammar advanced] make your blog more exciting (IV: set font style and color comparison table)
Nodejs ctf 基础
Directional crawling Taobao product name and price (teacher Songtian)
08 [AIO programming]
字符串——344.反转字符串
如何从功能测试到自动化测试?
链表——剑指offer面试题 02.07. 链表相交
Altium one key automatic BOM
Microservice - eruka