LeetCode:01:Two Sum

题目描述:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

题目分析:

给定一个数组和一个正整数,返回数组中和为正整数的下标,数组中的值只能使用一次。

算法思路:

首先对数组进行排序,考虑到排序后下标可能与原数组下标不一致,所以创建一个结构体,保存数组的值和下标。
用两个指针,分别从第一个和最后一个开始,如果和大于目标值,则后面的指针向前移动,如果和小于目标值,前面的指针向后移动,直到和等于目标值。

struct Node{
    int val;
    int idx;
    Node(int val,int idx):val(val),idx(idx){};
};

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> res;
        vector<struct Node> node;
        for(int i=0;i<nums.size();i++){
            node.push_back(Node(nums[i],i));
        }
        for(int i=0;i<node.size();i++){
            for(int j=0;j<i;j++){
                if(node[i].val<node[j].val){
                    Node tem=node[i];
                    node[i]=node[j];
                    node[j]=tem;
                }
            }
        }
        int i=0,j=node.size()-1;
        while(i!=j){
            if(node[i].val+node[j].val>target){
                j--;
            }
            else if(node[i].val+node[j].val<target){
                i++;
            }else {
                res.push_back(node[i].idx);
                res.push_back(node[j].idx);
                return res;
            }
        }
        return res;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值