[LeetCode]1.Two Sum

【题目】

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

【分析】

类似于剑指Offer之和为S的两个数字

【代码】

/*********************************
*   日期:2015-01-15
*   作者:SJF0115
*   题目: 1.Two Sum
*   网址:https://oj.leetcode.com/problems/two-sum/
*   结果:AC
*   来源:LeetCode
*   博客:
**********************************/
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        vector<int> result;
        vector<int> num = numbers;
        int count = numbers.size();
        if(numbers.empty()){
            return result;
        }//if
        // 排序
        sort(numbers.begin(),numbers.end());
        // 二分查找变形
        for(int i = 0,j = count-1;i < j;){
            int sum = numbers[i] + numbers[j];
            // 找到目标
            if(sum == target){
                return FindIndex(num,numbers[i],numbers[j]);
            }
            // 当前和大于目标,需要变小一些
            else if(sum > target){
                j--;
            }
            // 当前和小于目标,需要变大一些
            else{
                i++;
            }
        }//for
        return result;
    }
private:
    // 寻找下标
    vector<int> FindIndex(vector<int> &numbers,int num1,int num2){
        int count = numbers.size();
        vector<int> result;
        int index1,index2;
        bool flag1 = false,flag2 = false;
        for(int i = 0;i < count;++i){
            if(flag1 == false && numbers[i] == num1){
                index1 = i+1;
                flag1 = true;
            }
            else if(flag2 == false && numbers[i] == num2){
                index2 = i+1;
                flag2 = true;
            }
        }//for
        // 交换 使index1 < index2
        if(index1 > index2){
            int tmp = index1;
            index1 = index2;
            index2 = tmp;
        }//if
        result.push_back(index1);
        result.push_back(index2);
        return result;
    }
};

int main(){
    Solution solution;
    vector<int> num;
    num.push_back(0);
    num.push_back(4);
    num.push_back(3);
    num.push_back(0);
    //num.push_back(15);
    int target = 0;
    // 查找
    vector<int> vec = solution.twoSum(num,target);
    // 输出
    cout<<"Index1->"<<vec[0]<<" Index2->"<<vec[1]<<endl;
    return 0;
}

时间: 2024-10-23 15:58:41

[LeetCode]1.Two Sum的相关文章

c语言-求大神帮忙 C语言 LeetCode的 Two Sum问题

问题描述 求大神帮忙 C语言 LeetCode的 Two Sum问题 求大神帮忙.我run时显示Runtime Error,不知道问题在哪里.. 还有,我也不理解注释中的: * Note: The returned array must be malloced, assume caller calls free(). 这句是什么意思 题目: Given an array of integers, find two numbers such that they add up to a specif

[LeetCode]40.Combination Sum II

[题目] Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. Each number in C may only be used once in the combination. Note: All numbers (including target) will be

[LeetCode] Design Excel Sum Formula 设计Excel表格求和公式

Your task is to design the basic function of Excel and implement the function of sum formula. Specifically, you need to implement the following functions: Excel(int H, char W): This is the constructor. The inputs represents the height and width of th

LeetCode之K sum problem

做过leetcode的人都知道, 里面有2sum, 3sum(closest), 4sum等问题, 这些也是面试里面经典的问题, 考察是否能够合理利用排序这个性质, 一步一步得到高效的算法. 经过总结, 本人觉得这些问题都可以使用一个通用的K sum求和问题加以概括消化, 这里我们先直接给出K Sum的问题描述和算法(递归解法), 然后将这个一般性的方法套用到具体的K, 比如leetcode中的2Sum, 3Sum, 4Sum问题. 同时我们也给出另一种哈希算法的讨论. leetcode求和问题

[LeetCode]113.Path Sum II

[题目] Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. For example:Given the below binary tree and sum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1 return [ [5,4,11,2], [5,8,4,5] ] [分析] 题目要求求出所有路径

[LeetCode]39.Combination Sum

[题目] Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. The same repeated number may be chosen from C unlimited number of times. Note: All numbers (including target)

[LeetCode]--112. Path Sum

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. For example: Given the below binary tree and sum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1 return tru

[LeetCode]--303. Range Sum Query - Immutable

Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. Example: Given nums = [-2, 0, 3, -5, 2, -1] sumRange(0, 2) -> 1 sumRange(2, 5) -> -1 sumRange(0, 5) -> -3 Note: You may assume that the array do

&lt;font color=&quot;red&quot;&gt;[置顶]&lt;/font&gt;

Profile Introduction to Blog 您能看到这篇博客导读是我的荣幸,本博客会持续更新,感谢您的支持,欢迎您的关注与留言.博客有多个专栏,分别是关于 Windows App开发 . UWP(通用Windows平台)开发 . SICP习题解 和 Scheme语言学习 . 算法解析 与 LeetCode等题解 . Android应用开发 ,而最近会添加的文章将主要是算法和Android,不过其它内容也会继续完善. About the Author 独立 Windows App 和