(java)leetcode-1
来源:互联网 发布:分支界限算法 编辑:程序博客网 时间:2024/06/05 04:32
Two Sum
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:Gevin nums = [2,7,11,15],target = 9,
Because nums[0]+nums[1] = 2+7 = 9,
return [0,1].
这道题比较简单的一点就是有且只有一组值能够满足,所以不用考虑太多的情况。(一开始想多了...)
解题思路:
1. 暴力求解
直接对数组进行遍历,对于数组中的每一个元素,查找数组后面的元素中是否有满足条件的,有就直接返回。比较粗暴。时间复杂度是o(n^2),空间复杂度是o(1)
public class Solution { public int[] twoSum(int[] nums, int target) { int len = nums.length; int[] answer = new int[2]; for(int i = 0;i<len;i++) { int another = target - nums[i]; for(int j = i+1;j<len;j++) { if(nums[j] == another) { answer[0] = i; answer[1] = j; return answer; } } } return answer; }}
2.使用HashMap
用HashMap来存储一对数据<数值,位置>,从前向后遍历,用target减去元素值得到目标值,查找HashMap中是否有与目标值相同的Key,满足则返回结果。时间复杂度o(n),空间复杂度o(n)
import java.util.HashMap;public class Solution { public int[] twoSum(int[] nums, int target) { int len = nums.length;int[] answer = new int[2];HashMap<Integer,Integer> trace = new HashMap<Integer,Integer>();for(int i = 0;i<len;i++){int another = target - nums[i];if(trace.containsKey(another)){answer[0] = trace.get(another);answer[1] = i;break;}trace.put(nums[i], i);}return answer; }}
0 0
- (java)leetcode-1
- Leetcode 1(Java)
- LeetCode 1 Two sum Java
- [leetcode-1]Two Sum(java)
- LeetCode 1 - Two Sum ( JAVA )
- LeetCode【1】-Two Sum JAVA
- leetcode#1-Two Sum-java
- Leetcode(java)
- leetcode java
- [leetcode NO.1] Two Sum (JAVA)
- LeetCode 1 Two Sum for java
- Leetcode-1 Two Sum(Java) -by zzy
- 【leetcode with java】1 Two Sum
- [LeetCode][Java] Number of 1 Bits
- 【leetcode】【Numbers of 1 bits】java >>> &符号
- LeetCode|Number of 1 Bits-java
- (java)leetcode Number of 1 Bits
- Leetcode: 191. Number of 1 Bits(JAVA)
- J2SE习题—java基础
- Jedis分片连接池(分布式)
- Jquery 延时加载图片
- 动态当前时间
- webgate 重构 工作进度计划
- (java)leetcode-1
- 多线程基础课程
- mssql 根据出生日期计算年龄
- webpack安装和命令行
- 未来12个趋势
- 看门狗的使用与原理
- Visual Studio 良好的环境配置习惯 & 常用的宏
- 用深度优先遍历求全排列
- eclipse package explorer视图中怎么让default package不显示?