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行左右的代码就能实现。
只要你能鼓起勇气,克服因为未知而产生的恐惧,花一点时间和耐心去学习,将会看到一个完全不一样的世界。
阅读全文
0 0
- Leet Code OJ 1. Two Sum [Difficulty: Easy]
- Leet Code OJ 1. Two Sum [Difficulty: Easy]
- Leet Code OJ 1. Two Sum [Difficulty: Easy]
- Leet Code OJ 1. Two Sum [Difficulty: Easy]
- Leet Code OJ 231. Power of Two [Difficulty: Easy]
- Leet Code OJ 21. Merge Two Sorted Lists [Difficulty: Easy]
- Leet Code OJ 112. Path Sum [Difficulty: Easy]
- Leet Code OJ 292. Nim Game [Difficulty: Easy]
- Leet Code OJ 242. Valid Anagram [Difficulty: Easy]
- Leet Code OJ 258. Add Digits [Difficulty: Easy]
- Leet Code OJ 226. Invert Binary Tree [Difficulty: Easy]
- Leet Code OJ 283. Move Zeroes [Difficulty: Easy]
- Leet Code OJ 217. Contains Duplicate [Difficulty: Easy]
- Leet Code OJ 169. Majority Element [Difficulty: Easy]
- Leet Code OJ 263. Ugly Number [Difficulty: Easy]
- Leet Code OJ 100. Same Tree [Difficulty: Easy]
- Leet Code OJ 70. Climbing Stairs [Difficulty: Easy]
- Leet Code OJ 202. Happy Number [Difficulty: Easy]
- 树莓派3与树莓派2对比
- 15T3T4M操作技巧
- 作用域 scope 与rootscope
- AngularJS
- AngularJS
- Leet Code OJ 1. Two Sum [Difficulty: Easy]
- AngularJS
- ui-grid(1)--基础
- C语言模拟实现C++的多态
- 15的外部中断INT3和INT4
- ui-gird(2)--配置
- JS中的正则表达式
- ui-router的使用
- AngularJS 基础笔记