当前位置:网站首页>Sum of two numbers, sum of three numbers (sort + double pointer)
Sum of two numbers, sum of three numbers (sort + double pointer)
2022-07-05 23:02:00 【BugMaker-shen】
List of articles
One 、 And for s Two numbers of
Ascending , Use double pointer to traverse
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
int l = 0;
int r = nums.size() - 1;
while(l < r){
if(nums[l] + nums[r] == target){
return {
nums[l], nums[r]};
}else if(nums[l] + nums[r] > target){
r--;
}else{
l++;
}
}
return {
};
}
};
Two 、 Sum of two numbers
And hash table storage has been traversed and not found and for target Number of numbers ,key Value ,value Subscript the element
use target Subtract the number of current traversals , Look up... In the hash table , Find it and return the current subscript (i) And the subscript taken from the hash table (target - nums[i]). If not, save the current element value and subscript in the hash table
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
unordered_map<int, int> mp; // mp[val] = index
for(int i = 0; i < nums.size(); i++){
if (mp.find(target - nums[i]) != mp.end()){
return {
i, mp[target - nums[i]]};
}else{
mp[nums[i]] = i;
}
}
return {
};
}
};
3、 ... and 、 Sum of three numbers

Sort with + The double pointer method , The time complexity is O ( N 2 ) O(N^2) O(N2)
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
sort(nums.begin(), nums.end(), less<int>());
set<vector<int>> ans;
for(int l = 0; l < (int)nums.size() - 2 && nums[l] <= 0; l++){
int mid = l + 1;
int r = nums.size() - 1;
while(mid < r){
int sum = nums[l] + nums[mid] + nums[r];
if(sum == 0){
ans.insert({
nums[l], nums[mid], nums[r]});
r--;
while (mid < r && nums[r] == nums[r + 1]) r--; // while Circulation is used for weight removal
mid++;
while (mid < r && nums[mid] == nums[mid - 1]) mid++; // while Circulation is used for weight removal
}else if(sum > 0){
r--;
while (mid < r && nums[r] == nums[r + 1]) r--; // while Circulation is used for weight removal
}else{
mid++;
while (mid < r && nums[mid] == nums[mid - 1]) mid++; // while Circulation is used for weight removal
}
}
}
return vector<vector<int>> (ans.begin(), ans.end());
}
};

Four 、 The closest sum of three
unsorted , Direct violence backtracking , Overtime
class Solution {
public:
vector<int> choice;
int gap = INT_MAX;
int target_;
int ans;
void func(int i, const vector<int>& nums){
if(choice.size() == 3){
int sum = accumulate(choice.begin(), choice.end(), 0);
if (abs(target_ - sum) < gap) {
ans = sum;
gap = abs(target_ - sum);
}
}else{
for(int j = i; j < nums.size(); j++){
choice.push_back(nums[j]);
func(j + 1, nums);
choice.pop_back();
}
}
}
int threeSumClosest(vector<int>& nums, int target) {
target_ = target;
func(0, nums);
return ans;
}
};

Sort + Double pointer
class Solution {
public:
int threeSumClosest(vector<int>& nums, int target) {
sort(nums.begin(), nums.end(), less<int>());
long ans = INT_MAX;
for(int l = 0; l < (int)nums.size() - 2; l++){
int mid = l + 1;
int r = nums.size() - 1;
while(mid < r){
int sum = nums[l] + nums[mid] + nums[r];
if(abs(sum - target) < abs(ans - target)){
// sum and target Distance reduction of , Update ans
ans = sum;
}
if(sum == target){
// And for target, Then distance target lately , by 0, Returns the current sum
return sum;
}else if(sum > target){
r--;
}else{
mid++;
}
}
}
return ans;
}
};
边栏推荐
- February 13, 2022 -5- maximum depth of binary tree
- Yiwen gets rid of the garbage collector
- [digital signal denoising] improved wavelet modulus maxima digital signal denoising based on MATLAB [including Matlab source code 1710]
- Global and Chinese markets of industrial pH meters 2022-2028: Research Report on technology, participants, trends, market size and share
- Tensor attribute statistics
- Global and Chinese market of diesel fire pump 2022-2028: Research Report on technology, participants, trends, market size and share
- Media query: importing resources
- Paddy serving v0.9.0 heavy release multi machine multi card distributed reasoning framework
- openresty ngx_lua正則錶達式
- Unity Max and min constraint adjustment
猜你喜欢

如何快速理解复杂业务,系统思考问题?

LeetCode145. Post order traversal of binary tree (three methods of recursion and iteration)

Starting from 1.5, build a micro Service Framework -- log tracking traceid

实现反向代理客户端IP透传

Thoroughly understand JVM class loading subsystem

All expansion and collapse of a-tree

MoCo: Momentum Contrast for Unsupervised Visual Representation Learning

【Note17】PECI(Platform Environment Control Interface)

Business introduction of Zhengda international futures company

Expectation, variance and covariance
随机推荐
Marginal probability and conditional probability
链表之双指针(快慢指针,先后指针,首尾指针)
分布式解决方案之TCC
媒体查询:引入资源
[speech processing] speech signal denoising and denoising based on MATLAB low-pass filter [including Matlab source code 1709]
openresty ngx_lua正则表达式
第十七周作业
Commonly used probability distributions: Bernoulli distribution, binomial distribution, polynomial distribution, Gaussian distribution, exponential distribution, Laplace distribution and Dirac delta d
The difference between MVVM and MVC
Spectrum analysis of ADC sampling sequence based on stm32
My experience and summary of the new Zhongtai model
我把开源项目alinesno-cloud-service关闭了
VIM tail head intercept file import
2022 R2 mobile pressure vessel filling review simulation examination and R2 mobile pressure vessel filling examination questions
Request preview display of binary data and Base64 format data
MoCo: Momentum Contrast for Unsupervised Visual Representation Learning
东南亚电商指南,卖家如何布局东南亚市场?
【Note17】PECI(Platform Environment Control Interface)
[untitled]
Hj16 shopping list


