解决两数之和 (Javascript, Java, C#, Swift, Kotlin, Python,C++, Golang)

aside section._1OhGeD · · 552 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

解决两数之和 (Javascript, Java, C#, Swift, Kotlin, Python,C++, Golang)



给定一个整数数组,返回两个数字的索引,以便它们加起来成为一个特定的目标。



您可以假定每个输入都只有一个解决方案,并且您可能不会两次使用同一元素。


举例:


给定数组 =[2, 7, 11, 15], 目标值 = 9,

因为nums[0]+ nums[1] = 2 + 7 = 9,

所以返回 [0,1].


思路:


我们定义一个字典来存储元素及其索引。

我们将一一检查元素。

 假设当前元素是a;

 我们将元素及其索引存储到字典中;

 并使用目标减去当前元素来获得差值b;

 我们检查映射是否可以使用b作为键来获取任何内容,如果该值不为空并且其索引也不相同,则得到答案。


Javascript:


twoSum =(nums, target)=> {

    let map = newMap;

    for(let i = 0; i< nums.length; i ++) {

       let a = nums[i];

       let b = target - a;

       let j = map.get(b);

       if(j !== undefined) {

         if(j !== i){

            return [i, j ];

         }

       }

       map.set(a, i);

    }


    return [];

}


console.log(twoSum([2,7,11,15],9))

console.log(twoSum([3,2,4],6))

console.log(twoSum([3,3],6))


Java:


importjava.util.*;

public classHelloWorld{

     publicstatic void main(String []args){

       System.out.println(Arrays.toString(twoSum(newint[]{2,7,11,15}, 9)));

       System.out.println(Arrays.toString(twoSum(newint[]{3,2,4}, 6)));

                       System.out.println(Arrays.toString(twoSum(newint[]{3,3}, 6)));

     }


            public static int[] twoSum(int[] nums, inttarget) {

                       Map<Integer,Integer> map = new HashMap<Integer, Integer>();

                       for(int i = 0 ; i<nums.length; i++){

                                                int a = nums[i];

                                                int b = target - a;

                                                Integer j = map.get(b);

                                               map.put(a, i);

                                                if(j != null && i != j) {

                                                            return new int[]{i,j};

                                                }

                       }

                       return new int[]{};

    }

}


c#:


usingSystem;

usingSystem.Collections.Generic;

classHelloWorld {

    public staticvoid Main(string[] args)

    {


       Console.WriteLine(string.Join(",",twoSum(newint[]{2,7,11,15}, 9)));

       Console.WriteLine(string.Join(",",twoSum(new int[]{3,2,4},6)));

       Console.WriteLine(string.Join(",",twoSum(new int[]{3,3},6)));

    }


    public staticint[] twoSum(int[] nums, inttarget) {

            Dictionary<int,int> map= new Dictionary<int, int>();

            for(inti = 0 ; i<nums.Length; i++) {

                        int a = nums[i];

                        int b = target - a;

            if(map.ContainsKey(b)) {

                int j = map[b];

                if(i != j) {

                    return new int[]{i,j};

                }                    

            }

            map[a] = i;

            }

            returnnew int[]{};

    }

}


Swift:


importFoundation


functwoSum(_ nums: [Int], _ target:Int) -> [Int] {

    var map = [Int :Int]()

    for (i, a) innums.enumerated() {

       var b = target - a;

       var j = map[b]

       if(j != nil) {

           var jj = j!

           return [i,jj]

       }

       map[a] = i

    }

    return []

}


print(twoSum([2,7,11,15],9))

print(twoSum([3,2,4],6))

print(twoSum([3,3],6))


Kotlin:


funtwoSum(nums: IntArray, target:Int): IntArray {

    valmap:HashMap<Int,Int> =HashMap<Int,Int>()

    for ((i, a) innums.withIndex()) {

            varb = target - a

       var j = map.get(b)

       if(j != null) {

           var jj = j!!

           if(jj != i){

               return intArrayOf(i, j)

           }

       }

       map.set(a, i)

           }


    returnintArrayOf()

}


fun main() {

   println(twoSum(intArrayOf(2,7,11,15),9).joinToString(","))

    println(twoSum(intArrayOf(3,2,4),6).joinToString(","))

   println(twoSum(intArrayOf(3,3),6).joinToString(","))

}



Python:


deftwoSum(nums, target):

    map = {}

    i = 0

    l = len(nums)

    while i < l:

       a = nums[i]

       b = target - a

       j = map.get(b)

       if j is not None:

           if j != i:

               return [i,j]

       map[a] = i

       i += 1

    return[]   

print(twoSum([2,7,11,15],9))

print(twoSum([3,2,4],6))

print(twoSum([3,3],6))


C++:


#include<iostream>

#include<vector>

#include<map>


usingnamespace std;

vector<int>twoSum(vector<int>&nums, int target) {

    std:map<int,int> map;

    vector<int>ret;

    for(int i = 0; i< nums.size(); i ++) {

       int a = nums[i];

       int b = target - a;

       std::map<int,int>::iterator it =map.find(b);

       if(it != map.end()) {

           int j = it->second;

           if(j != i) {

               ret.push_back(i);

               ret.push_back(j);

              return ret;

           }

       }


       map.insert(std::pair<int, int>(a,i));

    }

    return ret;

}

int main()

{

    {

       std::vector<int> nums;

       nums.push_back(2);

       nums.push_back(7);

       nums.push_back(11);

       nums.push_back(15);

       std::vector<int> ret =twoSum(nums, 9);

       for (std::vector<int>::iteratorit = ret.begin() ; it != ret.end(); ++it){

           std::cout << *it <<',';

       }

       std::cout << '\n';

    }

    {

       std::vector<int> nums;

       nums.push_back(3);

       nums.push_back(2);

       nums.push_back(4);

       std::vector<int> ret =twoSum(nums, 6);

       for (std::vector<int>::iteratorit = ret.begin() ; it != ret.end(); ++it){

           std::cout << *it <<',';

       }

       std::cout << '\n';

    }

    {

       std::vector<int> nums;

       nums.push_back(3);

       nums.push_back(3);

       std::vector<int> ret =twoSum(nums, 6);

       for (std::vector<int>::iteratorit = ret.begin() ; it != ret.end(); ++it){

           std::cout << *it <<',';

       }


       std::cout << '\n';

    }


    return 0;

}



Golang:


package main


import (

           "fmt"

)


functwoSum(nums []int, target int)[]int {

       var mapCheck = make(map[int]int)

       var a int

       var b int

           for i:=0; i < len(nums) ; i ++ {

                       a = nums[i]

                       b = target - a


                       if j, ok := mapCheck[b]; ok {

                                   if( j != i){

                                               return[]int{i,j}

                                   }

                       }


                       mapCheck [a] = i

           }

           return []int{}

}


func main(){

           fmt.Println(twoSum([]int{2,7,11,15},9))

           fmt.Println(twoSum([]int{3,2,4}, 6))

           fmt.Println(twoSum([]int{3,3}, 6))

}



有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:aside section._1OhGeD

查看原文:解决两数之和 (Javascript, Java, C#, Swift, Kotlin, Python,C++, Golang)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

552 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传