LeetCode记录-easy-001 Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

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

Example:

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

 

class Solution {
    public int[] twoSum(int[] nums, int target) {
        
    }
}

 

思路:使用HashMap<Integer ,Integer>。将HashMap的key设定为target-numbers[i],value设定为 i 。读取nums[i] ,然后只要判断target-numbers[ i ]是否在HashMap中即可,若在,则返回 i  和 nums.get(target - numbers[ i]);

方法类:

import java.util.HashMap;

public class Solution {
    public static int[] twoSum(int[] numbers, int target) {
        int[] res = new int[2];
        HashMap<Integer, Integer> nums = new HashMap<Integer, Integer>();

        for (int i = 0; i < numbers.length; ++i) {
            // add i-th number
            Integer a = nums.get(numbers[i]);
            if (a == null)
                nums.put(numbers[i], i);

            // find (target - numbers[i])
            a = nums.get(target - numbers[i]);
            if (a != null && a < i) {
                res[0] = a ;
                res[1] = i ;
                break;
            }
        }
        return res;
    }
}

 

测试类:

import java.util.Scanner;

public class Test extends Solution{

    public static void main(String[] args) {
        
        Scanner input = new Scanner(System.in);
        System.out.println("请输入数字,以逗号分隔:");
        String str = input.nextLine();
        String[] strs = str.split(",");
        int[] number = new int[strs.length];
for(int i=0 ;i<strs.length;i++){ number[i]=Integer.parseInt(strs[i]);     //将String类型转换为Int类型 }

      System.out.println("请输入值:");
      int a = input.nextInt();
      int result[] = twoSum(number, a);

          System.out.println("index1 = "+result[0]+" index2 = "+result[1]);  

    }  
}

 显示结果:

请输入数字,以逗号分隔:
2,7,11,15
请输入值:
9
index1 = 0 index2 = 1

 

posted on 2017-12-04 13:02  任性的大萝卜  阅读(76)  评论(0编辑  收藏  举报

导航