leetcode01-Two Sum之beats99.47%Java版本
2016-04-09 10:39
393 查看
我的leetcode击败90%之旅,该篇章主要完成使用Java实现算法,达到进入10%的阵营。这是第一篇Two Sum
全部代码下载:
Github链接:github链接,点击惊喜;
写文章不易,欢迎大家采我的文章,以及给出有用的评论,当然大家也可以关注一下我的github;多谢;
You may assume that each input would have exactly one solution.
Example:
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
2.第一思路使用hashmap保存数组的出现
2.使用桶记录出现的target-num,比使用hashmap更快 *击败99.47%
好的本章介绍到这里
来自伊豚wpeace(rlovep.com)
全部代码下载:
Github链接:github链接,点击惊喜;
写文章不易,欢迎大家采我的文章,以及给出有用的评论,当然大家也可以关注一下我的github;多谢;
1.题目简介:只给英文了
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].
UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.
2.我的思路:
1.循环记录每个数字,同时判断target-num是否出现过。是就输出2.第一思路使用hashmap保存数组的出现
2.使用桶记录出现的target-num,比使用hashmap更快 *击败99.47%
3.我的代码
public class Solution { //使用桶记录出现的target-num public int[] twoSum(int[] nums, int target) { int length=nums.length; int[] a=new int[]{0,0}; if(nums==null||length<=0) return a; int[] tars=new int[100000];//nums[i]正数的桶记录 int[] tarsf=new int[100000];//nums[i]负数的桶记录 for(int i=0;i<length;i++){ int k=target-nums[i]; if(k<0){ if(tarsf[-k]!=0){ a[0]=tarsf[-k]-1; a[1]=i; break; }else{ if(nums[i]<0) { tarsf[-nums[i]]=i+1; //i+1是为了将数组初始化的0区分开 } else tars[nums[i]]=i+1;//i+1是为了将数组初始化的0区分开 } }else{ if(tars[k]!=0){ a[0]=tars[target-nums[i]]-1; a[1]=i; break; }else{ if(nums[i]<0) { tarsf[-nums[i]]=i+1; } else tars[nums[i]]=i+1; } } } return a; } }
4.使用过的低效代码:
public class Solution { public int[] twoSum(int[] nums, int target) { int length=nums.length; int[] a=new int[]{0,0}; if(nums==null||length<=0) return a; Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int i = 0; i < nums.length; i++) { if (map.containsKey(target-nums[i])) { a[0]=map.get(target-nums[i]); a[1]=i; return a; } else { map.put(nums[i], i); } } return new int[]{0, 0}; } }
好的本章介绍到这里
来自伊豚wpeace(rlovep.com)
相关文章推荐
- Hibernate---单表操作
- Java中读取Properties文件
- 03.——Java语句的执行结构
- java IO
- 开源 免费 java CMS - FreeCMS1.9 全文检索
- JVM(1)--java内存模型
- 认真学spring官网,很容易找到spring4的jar包下载位置
- Spring装配对JSR-250的@Resourse的支持
- 【JAVA】别特注意,POI中getLastRowNum() 和getLastCellNum()的区别
- Java Web 基础知识篇
- LeetCode 242 -Valid Anagram ( JAVA )
- Java中printf()的用法
- Eclipse中JVM内存配置
- java,成员变量与方法参数或自定义的局部变量同名要用this,system.out.println(this)用法,
- SpringMVC 下载
- SpringMVC 上传下载(1)
- (java)蛇形矩阵(递归实现)
- Java并发编程中实现原子操作
- Win7下配置Java开发环境变量
- Java学习·多线程