leetcode 刷题题解(c++) 1.Two Sum (hash表,排序+二分查找)

题目描述:

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

解法:

a. 排序+二分查找

struct Node
{
    int num, pos;
};
bool cmp(Node a, Node b)
{
    return a.num < b.num;
}
class Solution {
public:
    vector twoSum(vector &numbers, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector result;
        vector tmp;
        for(int i=0;itmp[end].pos)
                {
                    result.push_back(tmp[end].pos+1);
                    result.push_back(tmp[beg].pos+1);
                }
                else
                {
                    result.push_back(tmp[beg].pos+1);
                    result.push_back(tmp[end].pos+1);
                }
                return result;
            }
            else if(tmp[beg].num+tmp[end].num>target)
                end--;
            else
                beg++;
        }
        return result;
    }
};

b.hash表

i)遍历两遍

class Solution {
public:
    vector twoSum(vector& nums, int target) {
        unordered_map num_map;
        vector res;
        for (int i = 0; i < nums.size(); i++) {
            num_map[nums[i]] = i;
        }
        for (int i = 0; i < nums.size(); i++) {
            int tmp = target - nums[i];
            if (num_map.find(tmp) != num_map.end() && num_map[tmp] != i){
                res.push_back(i);
                res.push_back(num_map[tmp]);
                break;
            }
        }
        return res;
    }
};
ii)遍历一遍

class Solution {
public:
    vector twoSum(vector& nums, int target) {
        unordered_map num_map;
        vector res;
        for (int i = 0; i < nums.size(); i++) {
            int tmp = target - nums[i];
            if (num_map.find(tmp) != num_map.end() && num_map[tmp] != i){
                int beg = i > num_map[tmp] ? num_map[tmp] : i;
                int end = i > num_map[tmp] ? i : num_map[tmp];
                res.push_back(beg);
                res.push_back(end);
                break;
            }
            num_map[nums[i]] = i;
        }
        return res;
    }
};

你可能感兴趣的:(leetcode,刷题记录)