当前位置:网站首页>Leetcode: hash table 07 (sum of three numbers)
Leetcode: hash table 07 (sum of three numbers)
2022-06-23 18:16:00 【Taotao can't learn English】
The first 15 topic . Sum of three numbers
Give you one containing n Array of integers nums, Judge nums Are there three elements in a,b,c , bring a + b + c = 0 ? Please find out all the triples that meet the conditions and do not repeat .
Be careful : Answer cannot contain duplicate triples .
Example :
Given array nums = [-1, 0, 1, 2, -1, -4],
The set of triples satisfying the requirement is :
[
[-1, 0, 1],
[-1, -1, 2]
]
This question ... To give up , Look at the solution . Ninety five percent of the tests passed , It shows that the idea is correct , It's just a timeout . Can't , The test sample is too long .
package com.programmercarl.hashtable;
import java.util.*;
/** * @ClassName sum3 * @Descriotion TODO * @Author nitaotao * @Date 2022/6/21 15:03 * @Version 1.0 **/
public class sum3 {
public static List<List<Integer>> threeSum(int[] nums) {
/** * Still usable hashmap, * Sum of three numbers , In fact, when the current two numbers are determined , The last number has been fixed . * You can get the first two numbers to , Then calculate the last number , To prevent the same , Three number sort as key */
List<List<Integer>> result = new ArrayList<>();
int temp;
HashMap<String, String> map = new HashMap<>();
for (int i = 0; i < nums.length - 2; i++) {
for (int j = i + 1; j < nums.length - 1; j++) {
// The third number
// temp = 0 - nums[i] - nums[j];
temp = -(nums[i] + nums[j]);
// Three number order , Descending
String key = order3(nums[i], nums[j], temp);
map.put(key, i + "#" + j + "=" + temp);
}
}
// Only what has appeared is correct
Set<String> set = new HashSet<>();
Set<String> keys = map.keySet();
for (String key : keys) {
for (int i = 0; i < nums.length; i++) {
// value
String valStr = map.get(key);
// The value currently being compared , Not necessarily
int value = Integer.parseInt(valStr.split("=")[1]);
if (value == nums[i]) {
// Then judge whether this number is your own
// If not , Add again
// Position comparison
// Location
String[] pos = valStr.split("=")[0].split("#");
if (!(pos[0].equals(String.valueOf(i)) || pos[1].equals(String.valueOf(i)))) {
set.add(key);
}
}
}
}
// Processing result set , duplicate removal
for (String res : set) {
List<Integer> resultList = new ArrayList<>();
String[] split = res.split("#");
resultList.add(Integer.valueOf(split[0]));
resultList.add(Integer.valueOf(split[1]));
resultList.add(Integer.valueOf(split[2]));
result.add(resultList);
}
return result;
}
/** * Sort by three numbers in descending order * * @param nums1 * @param nums2 * @param nums3 * @return */
public static String order3(int nums1, int nums2, int nums3) {
if (nums1 > nums2) {
if (nums1 > nums3) {
//nums1 Maximum
if (nums2 > nums3) {
return "" + nums1 + "#" + nums2 + "#" + nums3;
} else {
return "" + nums1 + "#" + nums3 + "#" + nums2;
}
} else {
//nums1 no nums3 Big
return "" + nums3 + "#" + nums1 + "#" + nums2;
}
} else {
//nums2>nums1
if (nums2 > nums3) {
if (nums1 > nums3) {
return "" + nums2 + "#" + nums1 + "#" + nums3;
} else {
return "" + nums2 + "#" + nums3 + "#" + nums1;
}
} else {
//nums1 Maximum
return "" + nums3 + "#" + nums2 + "#" + nums1;
}
}
}
}

My idea is to use hashmap do
Sum of three numbers , In fact, when the current two numbers are determined , The last number has been fixed .
You can get the first two numbers to , Then calculate the last number , To prevent the same , Three number sort as key
To prevent key duplication , Sort the elements first , In the key , The composition of the value is The position of the first element # The position of the second element = The value of the required element .
The symbol is simply marked as .
Because the two values determine , The third value has been determined , Whether there is or not , Save it first .
Go over it again , See if the third value is , If there is , And the position is not the value of the first two elements , The sequence is found successfully .==============================================================================
hhhhh
I'm looking at the solution , I need to read my ID number .
It's been a hard day .
1: If the array length <3 Go straight back to .
2: Array sorting , Ascending .
3: Starting from the first place , Create the first element on the right as the left pointer , The last element is the right pointer .
4: If the first element >0, The smallest element >0, Go straight back , Without looking at the .
5: If except for the first element , The next benchmark element is the same as the previous one , Then skip , Because the results repeat .
6: Take the base element as the first sum , Then the second and third sums , From the left pointer and the right pointer respectively .
7: The transformation law of the left and right pointers is similar to that of the reference elements , Do not repeat with your last element , Otherwise, the result will be repeated .
8: To the left 、 The right is different from the last one , according to sum Value carry of , value >0, Then subtract a little from the right , value <0, Add a dot to the left , After all, it is in ascending order . Until the left and right coincide , End of cycle .
9: The datum element keeps moving back .
public static List<List<Integer>> threeSum(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
// Length of array
int len = nums.length;
// When the length of the array is less than 3 when , immediate withdrawal
if (len < 3) {
return result;
}
// Sort the array , Ascending
Arrays.sort(nums);
for (int i = 0; i < len; i++) {
// If the starting element of the traversal is greater than 0, You just quit
// Because it's ascending , Indicates that the minimum values are greater than 0, End directly
if (nums[i] > 0) {
break;
}
// duplicate removal , When the starting value is equal to the previous element , Then the result will be the same as the previous one .
/** * Such as -1 -1 2 * Just calculate the first -1 Of , Will put the second -1 Included in * Then take the second -1 When calculating , The first one is repeated in the multi substitution . */
if (i > 0 && nums[i] == nums[i - 1]) {
continue;
}
// Left pointer
int left = i + 1;
// Right pointer
int right = len - 1;
// When left is not equal to right
while (left < right) {
// Add three numbers
int sum = nums[i] + nums[left] + nums[right];
// If it is equal to 0, Then add the result set
if (sum == 0) {
result.add(Arrays.asList(nums[i], nums[left], nums[right]));
// When moving the left and right pointers , First, judge the values of the left and right pointers , Skip if repeated
while (left < right && nums[left] == nums[left + 1]) {
left++;
}
// duplicate removal , because i unchanged , When this time r The value of the fetched number is the same as the previous one , So there is no need to calculate
while (left < right && nums[right] == nums[right - 1]) {
right--;
}
// When the left and right sides are not the same as the previous one
left++;
right--;
} else if (sum < 0) {
left++;
} else if (sum > 0) {
right--;
}
}
}
return result;
}

边栏推荐
- Mobile SSH connection tool
- Prevent users from submitting repeatedly in the uniapp project
- Paper reading (49):big data security and privacy protection (Kopp)
- Baidu AI Cloud product upgrade Observatory in May
- org.apache.ibatis.binding.BindingException: Invalid bound statement (not found):...
- Strong cache and negotiation cache in http
- "Tribute to a century old master, collect pocket book tickets"
- 2022年T电梯修理考试题库及模拟考试
- VNC Viewer方式的远程连接树莓派
- Paper reading (54):deepfool: a simple and accurate method to four deep neural networks
猜你喜欢

"Tribute to a century old master, collect pocket book tickets"

论文阅读 (50):A Novel Matrix Game with Payoffs of Maxitive Belief Structure

【C工具】------点阵模拟测试2

QML type: Loader

Paper reading (58):research and implementation of global path planning for unmanned surface vehicle based
![[unity] instructions for beginners of textanimator plug-in](/img/aa/a406c70a28931ac138e65787a0aabd.png)
[unity] instructions for beginners of textanimator plug-in
![微信小程序报错[ app.json 文件内容错误] app.json: app.json 未找到](/img/ab/5c27e1bb80ad662d1a220d29c328e0.png)
微信小程序报错[ app.json 文件内容错误] app.json: app.json 未找到

【Unity】插件TextAnimator 新手使用说明

3000帧动画图解MySQL为什么需要binlog、redo log和undo log

Regular expression use graph bed
随机推荐
计算机学院改考后,网络空间安全学院也改考了!南京理工大学计算机考研
Redis cluster
Implementing Domain Driven Design - using ABP framework - General guidelines
Revil - blackmail Virus Emergency Response
[Hyperf]Entry “xxxInterface“ cannot be resolved: the class is not instantiable
6 steps to teach you financial data mining preprocessing
Reinforcement learning series (I) -- basic concepts
What if the website is poisoned
Cryptography involved in IOT device end
Implementing Domain Driven Design - using ABP framework - repository
[learning notes] tidb learning notes (III)
Baidu AI Cloud product upgrade Observatory in May
A set of code to launch seven golang web frameworks at the same time
【故障公告】取代 memcached 的 redis 出现问题造成网站故障
Which securities company is good for opening a mobile account? Is online account opening safe?
【剑指Offer】45. 把数组排成最小的数
论文阅读 (48):A Library of Optimization Algorithms for Organizational Design
如何利用好每天的时间高效复习?
云原生行业应用崛起,从“可用”到“好用”有多远?
Crmeb second open SMS function tutorial
