Leetcode twosum
来源:互联网 发布:画江湖之换世门生知乎 编辑:程序博客网 时间:2024/06/05 06:23
描述:
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 thesame element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
You may assume that each input would have exactly one solution, and you may not use thesame element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
return [0, 1].
不得不说自己的办法太弱智,虽然AC了:
public class Solution { public int[] twoSum(int[] nums, int target) { int [] ans = {0,0}; for (int i = 0;i < nums.length-1 ;i++) { for (int j = i + 1;j < nums.length ;j++ ){ if((nums[i] + nums[j]) == target){ ans[0] = i; ans[1] = j; return ans; } } } return ans; }}
大神JAVA版本,复杂度O(N)
public class Solution { public int[] twoSum(int[] numbers, int target) { int[] result = new int[2]; Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int i = 0; i < numbers.length; i++) { if (map.containsKey(target - numbers[i])) { result[1] = i + 1; result[0] = map.get(target - numbers[i]); return result; } map.put(numbers[i], i + 1); } return result;}
大神Python版本
class Solution(object): def twoSum(self, nums, target): if len(nums) <= 1: return False buff_dict = {} for i in range(len(nums)): if nums[i] in buff_dict: return [buff_dict[nums[i]], i] else: buff_dict[target - nums[i]] = i
Python 版本解析:
0 0
- [leetcode]-twoSum
- [leetcode]twoSum
- LeetCode-TwoSum
- 【Leetcode】TwoSum
- LeetCode - TwoSum
- leetcode :twoSum
- leetcode TwoSum
- leetcode twosum
- leetcode--twoSum
- LeetCode twoSum
- LeetCode-TwoSum
- leetcode--twoSum
- leetcode TwoSum
- TwoSum leetcode
- leetcode:twosum
- leetcode:TwoSum
- LeetCode---TwoSum
- LeetCode-TwoSum
- hibernate实现多条件组合的模糊查询
- java实现——2001计算两点间的距离
- Firefox在input标签padding上下边距过大时的bug现象
- MERGE语句用来合并UPDATE和INSERT语句,一张表的大数据操作,要同时进行增删改,提高性能
- 中国剩余定理(非互质)hdu3579 Hello Kiki ====注意刚好全部整除的情况
- Leetcode twosum
- 安装SQuirrel SQL Client连接Phoenix操作HBase
- jzoj 5001. 【NOI2017模拟3.4】Trie树 状压dp
- 利用摄像头拍照并保存
- 一个基于Behave框架的http接口测试实例
- C语言:顺序表
- Java常用设计模式
- 算法入门---java语言实现的冒泡排序小结
- [点分治 离线] BZOJ 4449 [Neerc2015]Distance on Triangulation