LeetCode【1】TwoSum
来源:互联网 发布:linux下vim配置文件 编辑:程序博客网 时间:2024/06/07 08:32
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,return [0, 1].
给定一个数组和一个target,如果两个数相加等于target,则返回的是两个元素的索引,这个数组中有或只有一对这样的数,一个元素只能使用一次
//1、蛮力法:这个思路很简单,就是两个for循环得到索引 时间复杂度为O(n²),空间复杂度为O(1)public static int[] sum1(int[] nums, int target) { for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[j] == target - nums[i]) { return new int[]{i, j}; } } } throw new IllegalArgumentException("没有合适的返回值");}//2、用空间换取时间:hashmap方法,先用一个map把数组内的元素都put进去,然后与target减去的进行对比// 用元素作为key,索引为value,时间复杂度为O(n),空间复杂度为O(n)public static int[] sum2(int[] nums, int target){ Map<Integer,Integer> map = new HashMap<Integer, Integer>(); for (int i = 0; i < nums.length; i++) { map.put(nums[i],i); } for (int i = 0; i < nums.length; i++) { int c = target - nums[i]; if(map.containsKey(c) && map.get(c) != i){ return new int[]{i,map.get(c)}; } } throw new IllegalArgumentException("没有合适的返回值");}//3、简化方法2中的代码,让两个for循环变成一个for循环,时间复杂度和空间复杂度和方法2一样,都是O(n)public static int[] sum3(int[] nums,int target){ Map<Integer,Integer> map = new HashMap<Integer, Integer>(); for (int i = 0; i <nums.length ; i++) { int c = target -nums[i]; if(map.containsKey(c)){ return new int[]{map.get(c),i}; } map.put(nums[i],i); } throw new IllegalArgumentException("没有合适的返回值");}
阅读全文
1 0
- leetcode 1----twoSum
- LeetCode 1 # TwoSum
- LeetCode 1 TwoSum
- leetcode 1 twoSum
- leetcode #1 TwoSum
- leetcode 1 TwoSum
- leetcode-1 TwoSum
- {Leetcode} 1。TwoSum
- [leetcode 1]TwoSum
- leetcode-1-TwoSum 哈希表
- [C++]LeetCode #1 twoSum
- leetcode 1 TwoSum
- LeetCode(1)--TwoSum
- Leetcode#1: twoSum
- 1-Leetcode-TwoSum
- LeetCode【1】TwoSum
- LeetCode#1-TwoSum
- leetcode 1:TwoSum (C#语言版)
- HDU 1070 Milk
- DrawerLayout的使用
- Qt 之 WAV文件属性计算(比特率、文件大小、文件时长)
- 习题三(1)
- activity_main.xml
- LeetCode【1】TwoSum
- java新手入门会犯的N个“超低级错误”
- listview_item01.xml
- 欢迎使用CSDN-markdown编辑器
- 跳跃游戏一(动态规划)
- ######纯注解ssh环境:crm系统===重点总结 概述(只有思想)
- 我的第一个程序
- listview_item02.xml
- Tablayout的基础使用