当前位置:网站首页>两数之和、三数之和(排序+双指针)
两数之和、三数之和(排序+双指针)
2022-07-05 22:50:00 【BugMaker-shen】
一、和为s的两个数字
升序,使用双指针遍历即可
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 {
};
}
};
二、两数之和
用和哈希表存储已经遍历过且没找到和为target的数,key为值,value为元素下标
用target减去当前遍历的数,在哈希表中查找,查找到就可以返回当前下标(i)和从哈希表取出的下标(target - nums[i])。没找到就在哈希表保存当前元素值以及下标
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 {
};
}
};
三、三数之和
用排序+双指针的方法,时间复杂度为 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循环用于去重
mid++;
while (mid < r && nums[mid] == nums[mid - 1]) mid++; // while循环用于去重
}else if(sum > 0){
r--;
while (mid < r && nums[r] == nums[r + 1]) r--; // while循环用于去重
}else{
mid++;
while (mid < r && nums[mid] == nums[mid - 1]) mid++; // while循环用于去重
}
}
}
return vector<vector<int>> (ans.begin(), ans.end());
}
};
四、最接近的三数之和
未排序,直接暴力回溯,超时
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;
}
};
排序+双指针
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和target的距离减小,则更新ans
ans = sum;
}
if(sum == target){
// 和为target,则距离target最近,为0,返回当前sum
return sum;
}else if(sum > target){
r--;
}else{
mid++;
}
}
}
return ans;
}
};
边栏推荐
- Distributed solution selection
- Hcip day 11 (BGP agreement)
- Hcip day 12 (BGP black hole, anti ring, configuration)
- Global and Chinese market of networked refrigerators 2022-2028: Research Report on technology, participants, trends, market size and share
- [screen recording] how to record in the OBS area
- Why does the C# compiler allow an explicit cast between IEnumerable&lt; T&gt; and TAlmostAnything?
- Event trigger requirements of the function called by the event trigger
- 2022 registration examination for safety management personnel of hazardous chemical business units and simulated reexamination examination for safety management personnel of hazardous chemical busines
- Starting from 1.5, build a micro Service Framework -- log tracking traceid
- Thinkphp5.1 cross domain problem solving
猜你喜欢
Thoroughly understand JVM class loading subsystem
Finally understand what dynamic planning is
Unity Max and min constraint adjustment
Distance from point to line intersection and included angle of line
MCU case -int0 and INT1 interrupt count
Expectation, variance and covariance
Masked Autoencoders Are Scalable Vision Learners (MAE)
The difference between MVVM and MVC
TCC of distributed solutions
Metasploit(msf)利用ms17_010(永恒之蓝)出现Encoding::UndefinedConversionError问题
随机推荐
【Note17】PECI(Platform Environment Control Interface)
Global and Chinese markets for reciprocating seal compressors 2022-2028: Research Report on technology, participants, trends, market size and share
傅里叶分析概述
实现反向代理客户端IP透传
Binary tree (III) -- heap sort optimization, top k problem
Exponential weighted average and its deviation elimination
Hcip day 11 (BGP agreement)
Global and Chinese markets of industrial pH meters 2022-2028: Research Report on technology, participants, trends, market size and share
I closed the open source project alinesno cloud service
[speech processing] speech signal denoising and denoising based on Matlab GUI low-pass filter [including Matlab source code 1708]
2022 G3 boiler water treatment simulation examination and G3 boiler water treatment simulation examination question bank
Element operation and element waiting in Web Automation
我把开源项目alinesno-cloud-service关闭了
The difference between MVVM and MVC
SPSS analysis of employment problems of college graduates
Starting from 1.5, build a micro Service Framework -- log tracking traceid
APK加固技术的演变,APK加固技术和不足之处
如何快速理解复杂业务,系统思考问题?
Overview of Fourier analysis
The method and principle of viewing the last modification time of the web page