Leetcode(1) Two Sum
2016-02-03 01:38
281 查看
https://leetcode.com/problems/two-sum/
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
今天开始从零单排leetcode, 纪念一些
这题比较简单,但也有几个细节需要注意。这题要求返回数的下标,注意是从1开始。
解法一:双指针暴力解法,时间复杂度O(n2),空间O(1)
解法2:Hashtable, 时间复杂度O(n), 空间复杂度O(1)
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
今天开始从零单排leetcode, 纪念一些
这题比较简单,但也有几个细节需要注意。这题要求返回数的下标,注意是从1开始。
解法一:双指针暴力解法,时间复杂度O(n2),空间O(1)
public class Solution { public int[] twoSum(int[] nums, int target) { int[] res = 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){ res[0] = i+1; res[1] = j+1; break; } } } return res; } }
解法2:Hashtable, 时间复杂度O(n), 空间复杂度O(1)
public class Solution { public int[] twoSum(int[] nums, int target) { int[] res = new int[2]; Map<Integer, Integer> map = new HashMap<>(); for(int i = 0; i < nums.length; i++){ if(map.containsKey(nums[i])){ res[0] = map.get(nums[i])+1; res[1] = i+1; break; }else{ map.put(target-nums[i], i); } } return res; } }
相关文章推荐
- 起点——2015年终总结
- addr2line 工具
- java面向对象的基础扫描
- 学习新技术方法感想
- ICPCCamp 2016 Day1 ftiasch's Contest #4(Around the world-树,构造)
- 【HDOJ】2890 Longest Repeated subsequence
- linux文件I/O
- DNS 主从实验
- JAVA中的匿名内部类
- python 多线程笔记(5)-- 生产者/消费者模式
- js获取浏览器高度和宽度值(多浏览器)
- DNS and BIND 笔记总结
- 计算A+B及其结果的标准形式输出
- 个人笔记 html 08 浏览器返回页面时刷新
- JAVA中的Object类
- linux运维实战练习-2016年1月19日-2月3日课程作业(练习)
- poj2778 DNA Sequence AC自动机 dp 矩阵乘法
- 安卓开发——requestFeature() must be called before adding content
- N!
- 数据类型