LeetCOde OJ Two Sum map应用

来源:互联网 发布:域名城论坛 编辑:程序博客网 时间:2024/06/06 09:22

Two Sum

 Total Accepted: 73626 Total Submissions: 410357

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

class Solution {public:    vector<int> twoSum(vector<int> &numbers, int target) {                vector<int> result;        map<int,int> mm;//数 和 位置        if(numbers.size()<2) return result;                for(int i=0;i<numbers.size();i++){            if(mm.count(target-numbers[i]))            {                result.push_back(mm[target-numbers[i]]+1);                result.push_back(i+1);                return result;            }else{                mm.insert(make_pair(numbers[i],i));            }        }    }};

public class Solution {    public int[] twoSum(int[] nums, int target) {        int[] result =new int[2];        HashMap<Integer,Integer> mm=new HashMap<Integer,Integer>();        if(nums.length<2)            return result;                    for(int i=0;i<nums.length;i++){            if(mm.get(target-nums[i])!=null){                result[0]=mm.get(target-nums[i])+1;                result[1]=i+1;                break;            }else{                mm.put(nums[i],i);            }        }        return result;    }}



0 0
原创粉丝点击