[leetcode] 1. Two Sum

来源:互联网 发布:淘宝刷票会被发现吗 编辑:程序博客网 时间:2024/05/31 19:15

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].

在数组中,找出相加和为target的数的数组下标(题目假设只有一个解,也就是数组每个元素唯一)

主要是利用的hash的思想,保存下标位置,查找时间为O(1),而不用每次去遍历数组。

public class Solution {    public int[] twoSum(int[] nums, int target) {        int[] result = new int[]{0,0};//返回值        Map<Integer, Integer> map = new HashMap<Integer, Integer>();        for (int i=0;i<nums.length;++i){            if(map.containsKey(target - nums[i])){ //如果之前的数中有和num[i]相加为target的数                //返回结果                result[0] = map.get(target-nums[i]);                result[1] = i;                break;            }else{                //把位置记录到map中                map.put(nums[i], i);            }        }        //System.out.println(result[0]+" "+result[1]);        return result;    }}
0 0
原创粉丝点击