1. Two Sum

来源:互联网 发布:cnnic数据 编辑:程序博客网 时间:2024/06/07 09:40

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 thesame element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].

Solution:

Tips:

1. How to record index of array.

2.

2.1 sort array, pick out a number from left and then pick out a number from right of the array. compare target with sum of left number and right. if sum equals to target stop, else if sum less than the target left forward one step, otherwise right step back.

2.2 try to use an appropriate data structure, such as hashmap.

Java Code

public class Solution {    public int[] twoSum(int[] nums, int target) {        // key --> value (val, idx)        Map<Integer, Integer> mii = new HashMap<>();        int leftIdx = 0;        int rightIdx = 0;        for (int i = 0; i < nums.length; i++) {            rightIdx = i;            if (mii.containsKey(target - nums[i])) {                leftIdx = mii.get(target - nums[i]);                break;            }            mii.put(nums[i], i);        }        int[] result = {leftIdx, rightIdx};        return result;    }}



0 0
原创粉丝点击