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

solution:暴力算法很显然是O(n2)会超时。

那么我的做法是把数组排序后二分查找。这样是O(n*lgn)。这里注意一个细节是类内的cmp比较函数要定义成静态成员函数,不然sort调用时会报错:invalid use of non-static member function。因为非静态成员函数是依赖于具体对象的,而std::sort这类函数是全局的,因此无法再sort中调用非静态成员函数。静态成员函数或者全局函数是不依赖于具体对象的, 可以独立访问,无须创建任何对象实例就可以访问。同时静态成员函数不可以调用类的非静态成员。

还有discuss里有更好的O(n)算法,就是hash的思想,利用unordered_map这一无序map来使查找的时间接近常数。unordered_map和map的区别是它无序,所以在不需要排序时最好使用它,比map更快。

class Solution {
public:
    struct node{
        node(int i,int v):id(i),val(v){}
        int id,val;
    };
    static bool cmp(node a,node b){
        return a.val<b.val;
    }
    vector<int> twoSum(vector<int>& nums, int target) {
        vector<node>vt;
        vector<int>ans;
        vector<int>::iterator it;
        int a1=0,a2=1;
        for(it=nums.begin();it!=nums.end();it++){
            vt.push_back(node(++a1,*it));
        }
        sort(vt.begin(),vt.end(),cmp);
        a1=0;
        for(it=nums.begin();it!=nums.end();it++){
            int t=*it;
            a1++;
            a2=lower_bound(vt.begin(),vt.end(),node(0,target-t),cmp)-vt.begin();
            int a3=upper_bound(vt.begin(),vt.end(),node(0,target-t),cmp)-vt.begin();
            if(a2<vt.size()&&a2==a3&&vt[a2].val==target-t&&vt[a2].id>a1){
                a2=vt[a2].id;
                //printf("index1=%d, index2=%d\n",a1,a2);
                ans.push_back(a1);
                ans.push_back(a2);
                return ans;
            }
            else if(a2<vt.size()&&vt[a2].val==target-t&&a2<a3){/*这个处理很有必要,不然[0,4,3,0]和target=0
            这组数据会WA,二分时要注意考虑有几个相等的情况*/
                for(int i=a2;i<a3;i++){
                    if(vt[i].id>a1){
                        ans.push_back(a1);
                        ans.push_back(vt[i].id);
                        return ans;
                    }
                }
            }

        }
        return ans;
    }
};

my answer

vector<int> twoSum(vector<int> &numbers, int target)
{
    //Key is the number and value is its index in the vector.
    unordered_map<int, int> hash;
    vector<int> result;
    for (int i = 0; i < numbers.size(); i++) {
        int numberToFind = target - numbers[i];

            //if numberToFind is found in map, return them
        if (hash.find(numberToFind) != hash.end()) {
                    //+1 because indices are NOT zero based
            result.push_back(hash[numberToFind] + 1);
            result.push_back(i + 1);
            return result;
        }

            //number was not found. Put it in the map.
        hash[numbers[i]] = i;
    }
    return result;
}

better answer in discuss

时间: 2024-10-05 13:56:39

leetcode 1 Two Sum(查找)的相关文章

LeetCode --- 1. Two Sum

题目链接: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. Plea

LeetCode:Range Sum Query - Immutable - 数组指定区间内的元素和

1.题目名称 Range Sum Query(数组指定区间内的元素和) 2.题目地址 https://leetcode.com/problems/range-sum-query-immutable/ 3.题目内容 英文:Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. 中文:给定一个数组nums,求出索引i和j之间元素的和,i一定是小于或等于j

【Leetcode】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]Path Sum 不同

LeetCode:Path Sum - 树的根节点到叶节点的数字之和

1.题目名称 Path Sum(树的根节点到叶节点的数字之和) 2.题目地址 https://leetcode.com/problems/path-sum/ 3.题目内容 英文: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. 中文:给定一颗二叉树,如

Java for LeetCode 216 Combination Sum III

Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers. Ensure that numbers within the set are sorted in ascending order. Example 1

LeetCode &quot;Minimum Path Sum&quot; - 2D DP

An intuitive 2D DP: dp[i][j] = min(grid[i-1][j-1] + dp[i-1][j], grid[i-1][j-1] + dp[i][j+1]) class Solution { public: int minPathSum(vector<vector<int> > &grid) { // dp[i][j] = min(dp[i-1][j] + dp[i][j], dp[i][j-1] + dp[i][j]); int n = gri

【LeetCode】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 true,

Leetcode:Minimum Path Sum 矩形网格最小路径和

Minimum Path Sum: Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. 解题分析: 每次只能向下或者向

[leetcode]Minimum Path Sum @ Python

原题地址:https://oj.leetcode.com/problems/minimum-path-sum/ 题意: Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or r

【LeetCode OJ】Sum Root to Leaf Numbers

? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 # Definition for a  binary tree node # class TreeNode: #     def __init__(self, x): #         self.val = x #         self.left = No