【LeetCode】算法修炼 --- Two Sum

Question:

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

Question Tags:

Array , Hash Table

New Words:

add up to:总计达

indices:index的复数

zero-based:从零开始的

Solution Ideas:

思路一:

两层遍历法:对于数组中的某一个数,对它及他以后的某个数求和,若和与target相等,则可确定这两值为所找的。

思路二:

HashMap--Value-key法:求a+b=target,也就是判断a和target-a是否都在这个数组中,

           遍历判断map中是否有数组中的某个值target-a,如果没有,则把a的key以value作为key存到map中,

           如果有,则所求的a,b得出来了。所求的索引值也就是a,b的索引值

两种方法都可以确保index1<index2.

Solution Java code:

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class TwoSum {

    public static void main(String[] args) {
        int[] numbers={2, 7, 11, 15};
        int target = 9;
        int[] twoSum = twoSum(numbers,target);
        System.out.println("two sum indices are " + twoSum[0] + "  and  " + twoSum[1]);

        int[] twoSum2 = twoSum2(numbers,target);
        System.out.println("two sum indices are " + twoSum2[0] + "  and  " + twoSum2[1]);
    }
        //思路1
    public static int[] twoSum(int[] numbers, int target) {
        int i,j,sum;
        int[] indices = new int[2];

        outfor:for (i=0;i<numbers.length;i++){
            for (j=i+1;j>i && j<numbers.length;j++){
                sum = numbers[i]+numbers[j];
                if (sum == target){
                    indices[0]=i+1;
                    indices[1]=j+1;
                   break outfor;
                }
            }
        }
        return indices;
    }
      //思路2
    public static int[] twoSum2(int[] numbers, int target) {

        int[] indices = new int[2];

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

        for (int i=0;i<numbers.length;i++){
            if (map.containsKey(target-numbers[i])){
                indices[0]=map.get(target-numbers[i]);
                indices[1]=i+1;
                break;
            }
            map.put(numbers[i],i+1);
        }
        return indices;
    }
}
时间: 2024-08-09 14:39:49

【LeetCode】算法修炼 --- Two Sum的相关文章

leetcode算法:Two Sum II - Input array is sorted

Given an array of integers that is already sorted in ascending order, 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 m

leetcode --day12 Surrounded Regions &amp; Sum Root to Leaf Numbers &amp; Longest Consecutive Sequence

1.  Surrounded Regions Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'. A region is captured by flipping all 'O's into 'X's in that surrounded region. For example, X X X X X O O X X X O X X O X X After running your fu

LeetCode算法编程(两题)

今天看到酷壳推荐的国外编程LeetCode算法编程网站,上面目前有154道算法题,感觉很有意思,平常工作也比较忙,现在很少有时间来锻炼算法相关的东西,有空的时候静下心来,温习下基础,活跃下自已的思路,也是有必要的.先做了几道,后面会陆续补充其它的题目. 1.题目-PlusOne Given a non-negative number represented as an array of digits, plus one to the number. The digits are stored s

LeetCode 64. Minimum Path Sum(最小和的路径)

Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. 题目标签:Array 这道题目和前面两题差不多,基本思想都是一样的

[LeetCode] Minimum Size Subarray Sum 解题思路

Given an array of n positive integers and a positive integer s, find the minimal length of a subarray of which the sum ≥ s. If there isn't one, return 0 instead. For example, given the array [2,3,1,2,4,3] and s = 7,the subarray [4,3] has the minimal

LeetCode算法题-Add Strings(Java实现)

这是悦乐书的第223次更新,第236篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第90题(顺位题号是415).给定两个非负整数num1和num2表示为字符串,返回num1和num2的总和. 注意: num1和num2的长度均<5100. num1和num2都只包含数字0-9. num1和num2都不包含任何前导零. 您不能使用任何内置BigInteger库或直接将输入转换为整数. 本次解题使用的开发工具是eclipse,jdk使用的版本是1.8,环境是win7 6

LeetCode算法题-Arranging Coins(Java实现)

这是悦乐书的第229次更新,第241篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第96题(顺位题号是441).您想要以楼梯形状形成总共n个硬币,其中每个第k行必须具有恰好k个硬币.给定n,找到可以形成的完整楼梯行的总数.n是一个非负整数,适合32位有符号整数的范围.例如: n = 5 硬币可以形成以下行: ¤ ¤¤ ¤¤ 因为第3行不完整,我们返回2. n = 8 硬币可以形成以下行: ¤ ¤¤ ¤¤¤ ¤¤ 因为第4行不完整,我们返回3. 本次解题使用的开发工具

LeetCode算法题-Convert BST to Greater Tree(Java实现)

这是悦乐书的第255次更新,第268篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第122题(顺位题号是538).给定二进制搜索树(BST),将其转换为更大树,使原始BST的每个键都更改为原始键加上所有键的总和大于BST中的原始键.例如: 输入:二进制搜索树的根,如下所示: 5 / 2 13 输出:大树的根,如下所示: 18 / 20 13 本次解题使用的开发工具是eclipse,jdk使用的版本是1.8,环境是win7 64位系统,使用Java语言编写和测试. 0

LeetCode算法题-Average of Levels in Binary Tree(Java实现)

这是悦乐书的第277次更新,第293篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第145题(顺位题号是637).给定一个非空二叉树,以数组的形式返回每一层节点值之和的平均值.例如: 3 / 9 20 / 15 7 输出:[3,14.5,11] 说明:第一层上的节点的平均值为3,第二层上的节点的平均值为14.5,第三层上的节点的平均值为11.因此返回[3,14.5,11]. 注意:节点值的范围在32位有符号整数的范围内. 本次解题使用的开发工具是eclipse,jd