twosum_两数之和_Leetcode_Easy1

开始刷leetcode了,算法小渣渣只先从简单地刷起。leetcode到目前为止共有944道。因为基础比较薄弱,打算在easy阶段,每天至少刷五道题。大概两个月完成。

第一道题就是十分经典的两数之和的题,虽然代码量很少,但是需要注意的点还是有很多的。

1.  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].

answer:

class Solution {
    public int[] twoSum(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {           //数组的值的长度:array_name.length
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {        //❗️==和=不要混淆
                    return new int[] { i, j };            //数组的初始化赋值,其中有一种是int a[] = new int[]{9,7,21}; 不需要定义数组的大小,数组会根据赋值大小分配空间
                }
            }
        }
        throw new IllegalArgumentException("No two sum solution");  //如果不写这行会报错:missing return statement,原因下面给出
    }
}

为什么如果不在函数体内抛出throw就会报错呢,因为虽然if/else里面已经有了return,但该逻辑语句在程序执行的过程中不一定会执行到,例如抛出异常等问题的出现,所以必须在try-catch外加一个return确保无论发生什么情况都会return.

复杂度分析:

由于这种算法是暴力算法,所以花费很多时间。

  • 时间复杂度:O(n2)
  • 空间复杂度:O(1)

算法改进:遍历两遍哈希表,时间复杂度是O(N),如果继续改进,遍历一遍哈希表,时间复杂度仅用O(1).

这两种方法之后补充。

猜你喜欢

转载自www.cnblogs.com/white-beauty/p/10022219.html