close

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

 

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

python:

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        # nums = [2,7,11,15], target = 9
        dict={}
        for i in range(len(nums)):
            a=target-nums[i]  #第一次跑a=7(跑12行)
            if a not in dict: #字典沒有7
                dict[nums[i]]=i #加入 {'2':0}
            else:
                return [ dict[a], i]

C++

class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        map<int,int>mp;
        for(int i=0;i<nums.size();i++)
        {mp[nums[i]]=i;}
        for(int i=0;i<nums.size();i++)
        {int a = target-nums[i] ;
            if(mp.count(a)&& mp[a]!=i){
                return {i,mp[a]};
            }
        }
        return {};
    }
};
arrow
arrow
    文章標籤
    python C++ leetcode
    全站熱搜
    創作者介紹
    創作者 趴趴熊日常 的頭像
    趴趴熊日常

    資工趴趴熊的小天地

    趴趴熊日常 發表在 痞客邦 留言(0) 人氣()