【LeetCode学习】【1:Two Sum】
来源:互联网 发布:cf怎么老是网络异常 编辑:程序博客网 时间:2024/06/06 02:48
题目描述:
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].
/// space O(1) , time O(n^2)public class Solution { public int[] twoSum(int[] nums, int target) { int[]res = new int[2]; for(int x = 0 ; x<nums.length-1; x++){ for( int y = x+1; y < nums.length; y++){ if(nums[x]+nums[y]==target){ res[0]= x; res[1]= y; break; } } } return res; }}
/// space O(n) , time O(n)public class Solution { public int[] twoSum(int[] nums, int target) { int []res= new int[2]; HashMap<Integer,Integer> checks = new HashMap<Integer,Integer>(); for(int i = 0 ; i < nums.length; i++){ //这说明这个nums[i]和之前放进的nums[i]相加刚好等于target, //也就是说target- nums[i]是之前放进去的那个nums[i], 那个i和这个i的下标就是所求数组的元素 if(checks.containsKey(target-nums[i])){ res[0] = checks.get(target-nums[i]) ; res[1] = i; break; }else{ checks.put(nums[i], i); } } return res; }}
阅读全文
0 0
- 【LeetCode学习】【1:Two Sum】
- LeetCode 学习笔记:Question 1、Two Sum
- LeetCode学习笔记[1]:Two Sum
- LeetCode 1 - Two Sum
- leetcode 1 Two Sum
- Leetcode【1】:Two Sum
- [leetcode 1] Two Sum
- 【leetcode-1】Two Sum
- [leetcode 1] Two Sum
- [Leetcode] 1 - Two Sum
- LeetCode (1) Two Sum
- LeetCode 1:《Two Sum》
- LeetCode | #1 Two Sum
- leetcode-1 Two Sum
- Two Sum | LeetCode(1)
- [Leetcode]1Two Sum
- leetcode 1 Two Sum
- leetcode #1 Two Sum
- AIDL相关笔记
- 华为云服务的使用方法详解--以照片备份与恢复为例
- 机器学习数学基础
- 微信 jssdk 语音监听播放结束的坑
- 建jini包
- 【LeetCode学习】【1:Two Sum】
- Maven:mirror和repository 区别
- const
- Android Studio平台下无线调试
- 统计难题——Trie树
- 使用PreparedStatement实现增删改查
- 怎样在main()函数退出之后再执行一段代码?
- xshell实现windows上传文件到linux
- 生成随机码