TwoSum
来源:互联网 发布:麦克风测试软件汉化 编辑:程序博客网 时间:2024/05/18 14:12
题目:
Created by Administrator on 2017/8/11. 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, and you may not use the same element twice.Example:Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].
解决方法:
1.传统方式,两个for循环
public int[] twoSum(int[] nums, int target) { int [] res = new int[2]; boolean flag = true; for(int i=0; i<nums.length && flag; i++){ for(int j=i+1; j<nums.length; j++){ if((nums[i] + nums[j]) == target){ res[0] = i; res[1] = j; flag = false; break; } } } if(res==null){ return null; }else { return res; }}
2.使用map
public int[] solution(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(target-nums[i])){ res[0] = i; res[1] = map.get(target-nums[i]); return res; } map.put(nums[i],i); } return null;}
阅读全文
0 0
- twoSum
- TwoSum
- TwoSum
- TwoSum
- twoSum
- TwoSum
- TwoSum
- TwoSum
- TwoSum
- TwoSum
- twoSum
- TwoSum
- twoSum
- TwoSum
- TwoSum
- twosum
- TwoSum
- TwoSum
- QAQ & ORZ 的签到题
- 暑假第11天总结
- linux中的高级网络配置
- 编程实现查找两个字符串的最大公共子串 示例:"aocdfe"和"pmcdfa"最大公共子串为"cfd"
- D
- TwoSum
- 3.1. Cross-validation: 评估 estimator 的性能
- UVA1204FunGame
- C语言入门:求一批整数中出现最多的数字
- 8月11日总结
- if __name__ == '__main__'到底干了什么?(关键词:Python、__name__、__main__)
- 笨办法学 Python · 续 第五部分:文本解析
- 2017 8.11
- SPOJ 7001 Visible Lattice Points (莫比乌斯反演+分块)