001 两数之和

题目

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target  的那 两个 整数,并返回它们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

你可以按任意顺序返回答案。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/two-sum

题解:双指针算法

  1. 对给定的nums数组进行升序排序
  2. 设定首指针L和尾指针R,使其分别指向数组的第一个和最后一个元素
    判断nums[L] + nums[R] 与给定target的关系:

    nums[L] + nums[R] == target    (得到答案元素)   
    nums[L] + nums[R]  <  target    (L指针右移继续遍历,直到两数和为target或首尾指针相遇)   
    nums[L] + nums[R]  >  target    (R指针右移继续遍历,直到两数和为target或首尾指针相遇)   
  3. c++代码
    //头文件
    #include <string>
    
    #include<iostream>
    
    #include<unordered_map>
    
    #include <algorithm>
    
    #include <sstream>
    
    #include <vector>
    
    //命名空间
    using namespace std;
    
    //Solution类,两数相加函数是类的成员函数
    class Solution {
    public:
        vector<int> twoSum(vector<int>& nums, int target);//成员函数在类内的声明
    };
    
    //成员函数在类外的具体实现
    //成员函数在类外实现要使用Solution::twoSum,函数名之前要加Solution::表明所属的类
    vector<int> Solution::twoSum(vector<int>& nums, int target) {
            
        int n = nums.size(); 
        //构造数组的索引数组idxs       
        vector<int> idxs;
        for(int i = 0; i < n; i++)idxs.push_back(i);
        //对数组进行升序排序
        sort(idxs.begin(),idxs.end(),[nums,idxs](int i, int j) {
            return nums[idxs[i]] < nums[idxs[j]];
        });
    
        //定义首尾指针
        int l = 0, r = n-1;
        //定义ret数组用于存放返回值,即和为target的两数组元素的下标
        vector<int> ret;
    
        //比较首尾指针指向元素和与target值并针对三种情况进行相应处理
        while (l < r){
            int sum = nums[idxs[l]] + nums[idxs[r]];
            if(sum == target){
                ret.push_back(idxs[l]);
                ret.push_back(idxs[r]);
                break;
            } else if (sum < target){
                l++;
            } else {
                r--;
            }
        }
        return ret;
    }
    
    //定义一个Solution类
    Solution s;
    
    
    //整型数组转字符串汉纳树
    string integerVectorToString(vector<int> list, int length = -1) {
        if (length == -1) {
            length = list.size();
        }
    
        if (length == 0) {
            return "[]";
        }
    
        string result;
        for(int index = 0; index < length; index++) {
            int number = list[index];
            result += to_string(number) + ", ";
        }
        return "[" + result.substr(0, result.length() - 2) + "]";
    }
    
    
    //主函数
    int main()
    
    {
        //示例数组与target值
        vector<int>nums={3,2,4};
        int target = 6;
    
        //调用twosum函数并将结果返回给ret数组
        vector<int> result = s.twoSum(nums,target);
        
        //将整型数组元素转换为string类型
        string out = integerVectorToString(result);
    
        //输出结果
        cout << out <<endl;
        return 0;
    
    }
    

猜你喜欢

转载自blog.csdn.net/fencecat/article/details/129653655
001