Leet Code OJ 1. Two Sum [Difficulty: Easy]

来源:互联网 发布:mac系统怎么建立文件夹 编辑:程序博客网 时间:2024/05/16 02:07

题目: 
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.

Example: 
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9, 
return [0, 1].

Java版代码1(时间复杂度O(n)):

public class Solution {    public int[] twoSum(int[] nums, int target) {        Map<Integer,Integer> map=new HashMap<>();        for(int i=0;i<nums.length;i++){            Integer index=map.get(target-nums[i]);            if(index==null){                map.put(nums[i],i);            }else{                return new int[]{i,index};            }        }        return new int[]{0,0};    }}
Java版代码2(时间复杂度O(n^2)):

public class Solution {    public int[] twoSum(int[] nums, int target) {        int[] result=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){                    return new int[]{i,j};                }            }        }        return result;    }}


算法!

      学了算法到底有没有用?

  以前我觉得没什么用,工作很长一段时间都没有用上。后来刷了LeetCode,在老大交给我的几个任务里都用到了一些,例如这一章译文中提到的哈希表,直接把某个数据筛选环节的运行时间从原来的半个小时缩短到10秒,速度足足提升了将近两百倍。

  算法并不是没有用,而是如果一个程序员不懂算法,在实际的编程中他就想不到用哪个算法比较好,只会一味用暴力算法或者是API自带的函数。我惊喜地发现,如果你开始懂一点算法,知道在什么情景下适用,将会带来超乎想象的好处。另一方面,也不要把算法想得那么高深和艰涩,大部分实用的算法都只是20行左右的代码就能实现。

   只要你能鼓起勇气,克服因为未知而产生的恐惧,花一点时间和耐心去学习,将会看到一个完全不一样的世界。



原创粉丝点击