2018.10.13学习笔记

10.13学习笔记

今天都在复习这周大学所学的课程,做了一个静态的简历网页,还挺好看的哈哈。到了晚上才有空坐下来,上了LeetCode刷了一道简单的算法题,下面总结下这道算法题的收获。

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].
题目简单意思就是:给定一个数组和一个目标值,找出数组中两个数相加之和为目标值的两个下标,返回一个存储了两个下标的数组,但是不能使用一个相同的元素两次。

解法1:

public class solution_1 {
    public int[] twoSum(int[] nums, int target) {
        for(int i = 0;i<nums.length - 1;i++){
            for(int j = i+1;i<nums.length;j++){
                if(nums[i] + nums[j] == target){
                    return new int[]{i,j};  //直接return new int[]{i,j} 
                }
            }
        }
        throw new IllegalArgumentException("no such sum solution");//抛出一个异常就不会报没有return语句的错误
    }

    public static void main(String args[]){
        solution_1 exercise_1 = new solution_1();
        int [] sums = {2,7,11,15};
        int target = 9;
        int [] result = exercise_1.twoSum(sums,target);
        for (int e:result){
            System.out.print(e + " ");
        }
    }
}

这是最容易想到的算法,算法的时间复杂度为O(n*n),空间复杂度为O(1)。

解法2:

/*
description:trade space for speed 用空间换取时间
             two iterations: first is store array to hashMap  O(n) = n;
 */

public class solution_2 {
    public int[] twoSum(int[] sums, int target) {
        HashMap<Integer,Integer> sumsMap = new HashMap<>();
        for (int i = 0;i<sums.length;i++){
            sumsMap.put(sums[i],i);   //hashMap 只能通过key获取value,因此把sum[i]作为key
        }

        for (int j = 0;j<sums.length;j++){
            int complement = target - sums[j];
            if (sumsMap.containsKey(complement) && complement != sums[j]){
                return new int[]{j,sumsMap.get(sums[j])};
            }
        }
        throw new IllegalArgumentException("no such solution");
    }
}

第二种解法,用空间换取时间,第一次使用iterator将数组中的职存储到hashMap中,然后在hashMap中查找有没有target—sums[j]的值,由于hashMap是使用散列来实现的,所以在hashMap中查找一个元素的时间复杂度为O(1)。这种算法的时间复杂度为O(n),空间复杂度也为O(n)。

解法3:

/*
description:use only one iterator to store array into hashMap,and varies to solution_2,solution_3 checked complement in one iterator
 */

public class solution_3 {
    public int[] twoSum(int[] sums, int target) {
        HashMap<Integer,Integer> map = new HashMap<>();
       for (int i = 0;i<sums.length;i++){
           int complement = target - sums[i];
           if (map.containsKey(complement)) {
               return new int[] { map.get(complement), i };
           }
           map.put(sums[i], i);
       }
       throw new IllegalArgumentException("no such solution");
    }
}

第三种解法优化了第二种解法,只使用了一次迭代,虽然与第二种方法的时间复杂度和空间复杂度都相同,但第三种解法明显优于第二种解法。

猜你喜欢

转载自blog.csdn.net/oQiShiYiGeRen/article/details/83043383