zoukankan      html  css  js  c++  java
  • LeetCode--Array--Two sum (Easy)

    1.Two sum (Easy)#

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

    solution##

    题意是给定一个int数组nums和一个整数target,在nums里面找到两数之和为target的数,并返回两数的数组索引。假定nums数组里面只有唯一的一组结果,且同一个数字只能使用一次。

    1.最容易想到的暴力算法,也就是我起初想到的!!!

    class Solution {
        public int[] twoSum(int[] nums, int target) {
            int[] indices = new int[2];
            for (int i = 0; i < nums.length - 1; i++)
            {
                for (int j = i + 1; j < nums.length; j++)
                {
                    if (nums[i] + nums[j] == target)
                    {
                        indices[0] = i;
                        indices[1] = j;
                        return indices;
                    }
                }
            }
            throw new IllegalArgumentException("No two sum solution");
        }
    }
    

    2.速度更快的解法,HashMap

    class Solution {
        public int[] twoSum(int[] nums, int target) {
            Map<Integer,Integer> m = new HashMap<Integer,Integer>();
            for (int i = 0; i < nums.length; i++)
            {
                int complement = target - nums[i];
                if (m.containsKey(complement))
                    return new int[] {m.get(complement),i};
                m.put(nums[i],i);
            }
            throw new IllegalArgumentException("No two sum solution");
        }
    }
    

    reference
    https://leetcode.com/articles/two-sum/

    总结##

    第一种暴力算法就是先取一个数,然后用这个数依次与后面的每一个数相加求和,若和与target相等,则将这两个数的数组索引加入到一个新的int数组中,然后返回这个int数组。time complexity:O(n^2),space complexity:O(1)


    第二种使用HashMap的方法起初不太容易想到。基本思路是将数组值作为键,索引作为值。是先创建一个hashmap,然后遍历数组nums,如果hashmap中已经存在complement=target-nums[i]这个元素,则将complement键对应的值(即数组索引),和i存到一个新的int数组里面并返回;若果不存在,则将nums[i],i分别作为键与值存到hashmap中去。如果遍历完数组没有找到相应的结果,则抛出异常。time complexity:O(n),space complexity:O(n)


    Notes
    1.数组值和下标互换是一种常用的技巧,不过只对整数有用;

  • 相关阅读:
    owlCarousel 用法心得1 -20170405
    js数组去重的四种方法
    js获取url参数值
    jq index()
    jQuery(expression,[context])
    音乐播放器的实现+显示当前时间的歌词(只显示当前时间的文本)
    iOS自动布局框架-Masonry详解
    ios -完全实现代码设置 Could not find a storyboard named 'Main' in bundle NSBundle
    Python使用MySQL数据库的
    iOS 阿里百川SDK集成注意点
  • 原文地址:https://www.cnblogs.com/victorxiao/p/11135576.html
Copyright © 2011-2022 走看看