leetcode:1. Two Sum

来源:互联网 发布:挂历制作软件下载 编辑:程序博客网 时间:2024/05/13 19:57

描述

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

思路

这题可以使用暴力搜索进行解决,不过时间消耗可能会有点大,我选择使用hash的思路来求解。遍历一遍,将数组中的每个数,映射到hash表中,并在hash表中记录位置。再遍历一遍,查找hash[target-index]是否为初始值,如果不是则返回index和hash[target-index]]的值。

代码

#include<iostream>#include <vector>#include <algorithm>#include <math.h>using namespace std;class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        vector<int>::iterator maxElement = max_element(nums.begin(), nums.end());        vector<int>::iterator minElement = min_element(nums.begin(), nums.end());        int max;        if(*maxElement < 0){            max = -(*minElement) * 2+1;        }        else if (* minElement > 0){            max = * maxElement * 2 + 1;        }        else{            if(abs(*maxElement) > abs(*minElement)){                max = 2 * abs(*maxElement) + 1;            }            else{                max = 2 * abs(*minElement) + 1;            }        }        cout << "max" << max << endl;        int hashPosArray[max];        int hashNegArray[max];        for(int i = 0; i < max; i++){            hashPosArray[i] = -1;            hashNegArray[i] = -1;        }        vector<int> indexArray;        int count = nums.size();        for(int i = 0; i < count; i++){            if(nums[i] >= 0 && nums[i] == target/2 && hashPosArray[nums[i]] != -1 ){                indexArray.push_back(i);                indexArray.push_back(hashPosArray[nums[i]]);                return indexArray;            }            else if(nums[i] <= 0 && nums[i] == target/2 && hashNegArray[-nums[i]] != -1){                indexArray.push_back(i);                indexArray.push_back(hashNegArray[-(target - nums[i])]);                return indexArray;            }            if(nums[i] >=0){                    hashPosArray[nums[i]] = i;            }            else{                    hashNegArray[-nums[i]] = i;            }        }        for(int i = 0; i < count; i++){        //  cout << i << "\t" <<nums[i] * (target-nums[i]) << endl;            if(nums[i] * (target-nums[i]) > 0){                if(nums[i] >= 0 && hashPosArray[target - nums[i]] != -1 && hashPosArray[target - nums[i]] != i){                    indexArray.push_back(i);                    indexArray.push_back(hashPosArray[target-nums[i]]);                    break;                }                else if(nums[i] < 0 && hashNegArray[-(target - nums[i])] != -1 && hashPosArray[-(target - nums[i])] != i){        //          cout << nums[i] << "\t" << -(target - nums[i]) << "\t" << hashNegArray[-(target - nums[i])] << endl;                    indexArray.push_back(i);                    indexArray.push_back(hashNegArray[-(target - nums[i])]);                    break;                }            }            else if(nums[i] * (target-nums[i]) < 0){            //  cout << "小于0" << target - nums[i] << endl;                 if(nums[i] >= 0 && hashNegArray[-(target - nums[i])] != -1 && hashNegArray[-(target - nums[i])] != i){                    indexArray.push_back(i);                    indexArray.push_back(hashNegArray[-(target-nums[i])]);                    break;                }                else if(nums[i] < 0 && hashPosArray[(target - nums[i])] != -1 && hashPosArray[target - nums[i]] != i){                //  cout << nums[i] << "\t" << (target - nums[i]) << "\t" << hashPosArray[(target - nums[i])] << endl;                    indexArray.push_back(i);                    indexArray.push_back(hashPosArray[(target - nums[i])]);                    break;                }            }        }        return indexArray;    }};int main(){    int nums[] = {3, 2, 4};    int nums_len =  sizeof(nums)/sizeof(nums[0]);    vector<int> varr(nums, nums + nums_len);    Solution add;    vector<int> index = add.twoSum(varr, 16021);    for(vector<int>::const_iterator iter = index.begin(); iter != index.end(); iter++){        cout << (*iter) << endl;    }    cout<<"hello world" << endl;    //return 0;}

PS:int hashPosArray[max];int hashNegArray[max];这两个数组的大小我最开始是指定10000,这样时间消耗有点大,运行的时间排在55%左右,我将这里数组大小改为自适应的,时间立马变小了,排到了92%。时间复杂度:2O(n);

结果

这里写图片描述

他山之玉

C++ O(n) solutioin

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;}

unordered_map官方文档
unordered_map博客简介

Java O(n) solution

public int[] twoSum(int[] numbers, int target) {    int[] result = new int[2];    Map<Integer, Integer> map = new HashMap<Integer, Integer>();    for (int i = 0; i < numbers.length; i++) {        if (map.containsKey(target - numbers[i])) {            result[1] = i + 1;            result[0] = map.get(target - numbers[i]);            return result;        }        map.put(numbers[i], i + 1);    }    return result;}

python O(n) solution

class Solution(object):    def twoSum(self, nums, target):        if len(nums) <= 1:            return False        buff_dict = {}        for i in range(len(nums)):            if nums[i] in buff_dict:                return [buff_dict[nums[i]], i]            else:                buff_dict[target - nums[i]] = i
0 0
原创粉丝点击