LeetCode 1 Two Sum

來源:互聯網
上載者:User

標籤:leetcode   twosum   

原題:

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=9Output: index1=1, index2=2

翻譯:

給定一個整型數組,找出能相加起來等於一個特定目標數位兩個數。函數twoSum返回這兩個相加起來等於目標值的數位索引,且index1必須小於index2。請記住你返回的答案(包括index1和index2)都不是從0開始的。你可以假定每個輸入都有且僅有一個解決方案。Input: numbers={2, 7, 11, 15}, target=9Output: index1=1, index2=2

C++

class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {        map<int, int> mapping;        vector<int> result;        for (int i = 0; i < nums.size(); i++)        {            mapping[nums[i]] = i;        }        for (int i = 0; i < nums.size(); i++)        {            int searched = target - nums[i];            if (mapping.find(searched) != mapping.end()                && mapping.at(searched) != i)            {                result.push_back(i + 1);                result.push_back(mapping[searched] + 1);                break;            }        }        return result;         }};

Java

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

著作權聲明:本文為 NoMasp柯於旺 原創文章,未經許可嚴禁轉載!歡迎訪問我的部落格:http://blog.csdn.net/nomasp

LeetCode 1 Two Sum

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.