LeetCode刷题系列_1题
来源:互联网 发布:js微信支付接口开发 编辑:程序博客网 时间:2024/06/05 14:58
题目要求:
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.
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
我的Solution:
int length = nums.length; int[] res = {}; int lastIndex = nums.length-1; ArrayList<Integer> result = new ArrayList<Integer>(); while(length > 0) { int last = nums[length-1]; for(int i=0;i<length-1;i++) { if(nums[i]+last == target) { result.add(i); result.add(lastIndex); res = new int[result.size()]; for (int j=0;j<result.size();j++) { res[j] = result.get(j); } return res; } } lastIndex -= 1; length -= 1; } return res;
跟我写的一个效率但是比我整洁的写法(反正都是暴力遍历求解,O(n2)的时间复杂度):
int length = nums.length; int index1 = 0; int index2 = 0; for (int i=0;i<length;i++) { for(int j=i+1;j<length;j++) { if(nums[i] + nums[j] == target) { index1 = i; index2 = j; } } } int[] returnValue = new int[] {index1, index2}; return returnValue;
O(n)复杂度的解法(想法很好)
public int[] twoSum(int[] nums, int target) { Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int j=0;j<nums.length;j++) { int x = nums[j]; if(map.containsKey(target-x)) { return new int[] { map.get(target-x), j }; } map.put(x, j); } throw new IllegalArgumentException("no two sum solution"); }
这就是差距啊,妈蛋,是个坑老子也要填平了!
0 0
- LeetCode刷题系列_1题
- LeetCode刷题系列
- [leetcode刷题系列]Permutations
- [leetcode刷题系列]Triangle
- [leetcode刷题系列]Subsets
- [leetcode刷题系列]Combinations
- [leetcode刷题系列]strStr
- [leetcode刷题系列]Anagrams
- 小程序员刷题之路_1
- 算法笔试题_1
- 规律题_1
- LeetCode刷题系列_15题
- LeetCode刷题系列_16题
- LeetCode刷题系列_2题
- LeetCode刷题系列_43题
- LeetCode刷题系列_66题
- LeetCode刷题系列_3题
- LeetCode刷题系列_5题
- Gradle加入Tomcat运行HelloWorld测试
- Spring原理(四)AOP的实现
- [2016/11/24]python数据类型之列表
- ini 配置文件的格式 及读取
- codeblocks代码自动补全(针对opencv)
- LeetCode刷题系列_1题
- 你所不知道的JavaScript的逻辑操作符
- 【js】JSON.stringify 语法实例讲解
- 第11周 项目1-验证算法(3)
- @WebFilter怎么控制多个filter的执行顺序
- C 语言入门(一)
- PHP rand和mt_rand 区别
- PHP代码运行流程
- 栈溢出利用SEH异常处理