leetcode解题记录

Practice 1:

题目描述:

给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。

你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。

示例:

给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

我的解答:

 1 class Solution {
 2    public int[] twoSum(int[] nums, int target) {
 3         int [] array = nums;
 4         int sum = target;
 5         int second;
 6         int first;
 7         for (int i = 0; i < array.length; i++) {
 8             first = array[i];
 9             second = sum - first;
10             for (int j = i+1; j <array.length ; j++) {
11                 if (second == array[j]){
12                     return new int[] {i,j};
13                 }
14             }
15         }
16         return null;
17     } 
18 }

更优解答案解析:

两遍哈希表

 1 public int[] twoSum(int[] nums, int target) {
 2     Map<Integer, Integer> map = new HashMap<>();
 3     for (int i = 0; i < nums.length; i++) {
 4         map.put(nums[i], i);
 5     }
 6     for (int i = 0; i < nums.length; i++) {
 7         int complement = target - nums[i];
 8         if (map.containsKey(complement) && map.get(complement) != i) {
 9             return new int[] { i, map.get(complement) };
10         }
11     }
12     throw new IllegalArgumentException("No two sum solution");
13 }
  • 时间复杂度:O(n), 我们把包含有 nn 个元素的列表遍历两次。由于哈希表将查找时间缩短到 O(1)) ,所以时间复杂度为 O(n)

  • 空间复杂度:O(n), 所需的额外空间取决于哈希表中存储的元素数量,该表中存储了 n 个元素。 

猜你喜欢

转载自www.cnblogs.com/Sherlin/p/9265028.html