Leetcode twosum

来源:互联网 发布:画江湖之换世门生知乎 编辑:程序博客网 时间:2024/06/05 06:23
描述:
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].
不得不说自己的办法太弱智,虽然AC了:
public class Solution {    public int[] twoSum(int[] nums, int target) {       int [] ans = {0,0};        for (int i = 0;i < nums.length-1 ;i++) {            for (int j = i + 1;j < nums.length ;j++ ){                if((nums[i] + nums[j]) == target){                    ans[0] = i;                    ans[1] = j;                    return ans;                }            }        }        return ans;        }}
大神JAVA版本,复杂度O(N)
public class Solution {    public int[] twoSum(int[] numbers, int target) {    int[] result = 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])) {            result[1] = i + 1;            result[0] = map.get(target - numbers[i]);            return result;        }        map.put(numbers[i], i + 1);    }    return result;}
大神Python版本
class Solution(object):    def twoSum(self, nums, target):        if len(nums) <= 1:            return False        buff_dict = {}        for i in range(len(nums)):            if nums[i] in buff_dict:                return [buff_dict[nums[i]], i]            else:                buff_dict[target - nums[i]] = i

Python 版本解析:


0 0
原创粉丝点击