two sum
来源:互联网 发布:星球大战 全介绍 知乎 编辑:程序博客网 时间:2024/06/14 21:44
question:
Given: an array of integers,
to do: find two numbers such that they add up to a specific target number.
requirement: 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
public class Solution{
public int[] twoSum(int[] nums, int target){
for(int i=0; i<nums.length; i++){
for(int j=0; j<nums.length; j++){
int sum = nums[i]+nums[j];
if(sum==target && (i<j>)){
System.out.println("Output: index1=" + (i+1) +", index2=" + (j+1));
}
}
}
return nums=null;
}
}
error message:; last executed input: time limited exceed.
using mapping
public class Solution{
public int[] twoSum(int[] nums, int target){
Map<Integer, Integer> map = new HashMap<>();
for(int i=0; i<nums.length; i++){
int x = nums[i];
if(map.containsKey(target - x)){
return new int[]{map.get(target - x) + 1, i+1};
}
map.put(x,i);
}
throw new IllegalArgumentException("No two sum solution");
}
}
brute force approach has O(n^2) run time and O(1) space.
hash table has O(n) run time and O(n) space.
- Two Sum
- Two Sum
- Two Sum
- two sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Two Sum
- Android官方刷新组件 SwipeRefreshLayout 的使用
- 流-到底是个啥……
- 【随笔】iOS9新特性介绍
- property替换方法名
- PHP中的socket_read和socket_recv区别详解
- two sum
- driver的总结
- EL隐式对象
- 地理杂志精选照片
- 进程的通信方式
- linux基础
- 2015.12.28
- 地理杂志精选照片
- JAVA子类方法重写父类方法