LeetCode-1. Two Sum
2016-03-28 21:07
302 查看
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:
最开始嘛,当然是暴力破解。
结果发现只击败了11%的用户。。。于是。。
然后就击败百分之三十多了。。
leetcode第一题~
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].
最开始嘛,当然是暴力破解。
public class Solution { public int[] twoSum(int[] nums,int target){ int N = nums.length; for(int i = 0; i<N; i++){ for(int j = i+1; j<N; j++){ if(nums[i] + nums[j] == target){ int[] re = {i,j}; return re; } } } return null; } }
结果发现只击败了11%的用户。。。于是。。
import java.util.Map; import java.util.HashMap; public class Solution { public int[] twoSum(int[] nums, int target) { Map<Integer,Integer> map = new HashMap<Integer,Integer>(); int[] res = new int[2]; for(int i = 0 ; i < nums.length ; i++){ map.put(nums[i], i); } for(int i = 0; i<nums.length;i++){ int gap = target-nums[i]; if(map.containsKey(gap) && map.get(gap)!=i){ res[0] = i; res[1] = map.get(gap); break; } } return res; } }
然后就击败百分之三十多了。。
leetcode第一题~
相关文章推荐
- Android中EventBus使用详解(一)
- iOS - UITableViewCell reload 数据刷新method
- 第四周项目5:程序分析
- Hibernate的初次使用
- JSP页面嵌套乱码解决
- Linux下MySQL 5.5/5.6的修改字符集编码为UTF8(彻底解决中文乱码问题)适用于centos 7
- 理解Linux系统/etc/init.d目录和/etc/rc.local脚本
- Node.js HTTP Server对象及GET、POST请求
- 仿微信朋友圈实现共享视图元素的切换动画
- spring+hibernate+struts+mysql
- Aizu 2249Road Construction 单源最短路变形 spfa模板改写
- Ajax使用方法
- 广播是建立于UDP基础上的,所以创建socket必须指定SOCK_DGRAM。
- 超链接 a href 提交表单通过post方式
- sublime text常用快捷键整理
- 在CentOS 7中安装与配置Tomcat-8方法
- hdu 1907 尼姆博弈变形 最后取得人为输
- Ubuntu下mongodb的安装与配置
- 项目1-三角形类雏形
- C#使用LitJson解析JSON