1. Two Sum

来源:互联网 发布:《读圣经》软件 编辑:程序博客网 时间:2024/06/10 06:18

Description Submission Solutions
  • Total Accepted: 439624
  • Total Submissions: 1405067
  • Difficulty: Easy
  • Contributors: Admin

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].

Subscribe to see which companies asked this question.

惯例翻译题目:

给出一个整形数组,以及一个数字,返回数组里面和等于该数字的两个数字的下标;给出的数组有且唯有一组解;

而且同一个数字不会用两次,一开始我的理解是不存在两个相同数字相加得到给定的数字;但是其实不是,是同一个下标的数字不会使用两次;

思路:

从第一个开始遍历,因为同一个数字不会用两次,所以直接从第一个数字开始遍历就可以;

这里面我一开始只考虑了两个正整数相加,其实不是,还存在正负,负正,0负,0正的组合;

从第一个开始遍历,用target-nums[i],然后从j=i+1遍历,遇到nums[j]==target-nums[i]则结束循环,然后

返回此时的i,j,由于此时返回的是<vector[int]>,因此要声明一个index,然后index.resize(2),赋值即可;

以下为代码:

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        int i,j,k,l,res;
        vector<int> index;
        bool flag=false;
        index.resize(2);
        for(i=0;i<nums.size();i++){
            //if(nums[i]>target){
              //  continue;
            //}
            //else{
                k=nums[i];
                res=target-nums[i];
                //j=i+1;
                for(j=i+1;j<nums.size();j++){
                    if(nums[j]==res){
                        flag=true;
                        index[0]=i;
                        index[1]=j;
                        //return index;
                        break;
                    }
                    else{
                        continue;
                    }
                }
                //if(flag){
                  //  break;
                //}
           // }
            //index.resize(2);
            //index[0]=i;
            //index[1]=j;
            
            //break;
        }
        return index;
        
    }
};

错位总结:

1.一开始只考虑了正数加上正数的情况,因此一开始设置如果nums[i]>=target,则去对nums[i+1]进行匹配;

然后在测试用例[0,3,8,0],8,没通过,这种情况是将“=”去掉即可;

2.去掉之后,在测试用例[-1,-5,-7,-8],-8没通过,也很简单,因为-1 + -7 =-8,而如果按照这个匹配条件,则会直接

跳过了-1,-5,-7了;

于是去掉了这个判断,直接用res记录target-nums[i]的值,然后从j=i+1开始遍历,遇到有相等的则直接跳出循环,返回i ,j;

另外一份代码示例:

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<int> index;
        index.resize(2);
        int i,j,k,l,res;
        k=nums.size();
        bool flag=false;
        for(i=0;i<k;i++){
            //if(nums[i]<target){
                res=target-nums[i];
                for(j=i+1;j<k;j++){
                    if(res==nums[j]){
                        flag=true;
                        index[0]=i;
                        index[1]=j;
                        break;
                    }
                }
            //}
            if(flag){
                break;
            }
        }
        return index;
        
    }
};

做题需要注意循环的跳出以及赋值是否赋给了正确的对象;

0 0
原创粉丝点击