TwoSum

来源:互联网 发布:麦克风测试软件汉化 编辑:程序博客网 时间:2024/05/18 14:12

题目:

 Created by Administrator on 2017/8/11. 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].

解决方法:

1.传统方式,两个for循环

public int[] twoSum(int[] nums, int target) {    int [] res = new int[2];    boolean flag = true;    for(int i=0; i<nums.length && flag; i++){        for(int j=i+1; j<nums.length; j++){            if((nums[i] + nums[j]) == target){                res[0] = i;                res[1] = j;                flag = false;                break;            }        }    }    if(res==null){        return null;    }else {        return res;    }}

2.使用map

public int[] solution(int[] nums, int target){    int[] res = new int[2];    Map<Integer,Integer> map = new HashMap<>();    for(int i = 0; i < nums.length; i++){        if(map.containsKey(target-nums[i])){            res[0] = i;            res[1] = map.get(target-nums[i]);            return res;        }        map.put(nums[i],i);    }    return null;}


原创粉丝点击