程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> LeetCode 1 Two Sum

LeetCode 1 Two Sum

編輯:C++入門知識

LeetCode 1 Two Sum


原題:

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

翻譯:

給定一個整型數組,找出能相加起來等於一個特定目標數字的兩個數。

函數twoSum返回這兩個相加起來等於目標值的數字的索引,且index1必須小於index2。
請記住你返回的答案(包括index1和index2)都不是從0開始的。

你可以假定每個輸入都有且僅有一個解決方案。

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

C++

class Solution {
public:
    vector twoSum(vector& nums, int target) {
        map mapping;
        vector 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 map=new HashMap();
        int[] result=new int[2];
        for(int i=0;i

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

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved