天天看点

1.力扣-数组-数组的遍历1

1.力扣-数组-数组的遍历1

1.最大连续1的个数(LeetCode485)

  • 题目概述:给定一个二进制数组, 计算其中最大连续 1 的个数。
  • 题目示例:

    输入:[1,1,0,1,1,1]

    输出:3

    解释:开头的两位和最后的三位都是连续 1 ,所以最大连续 1 的个数是 3.

  • 解题思路:这道题比较简单 只需要找两个变量,一个记录目前连续的最大值,一个记录从开始到现在的最大连续值
  • java代码
class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int maxLong=0;
        int temp=0;
        for(int num:nums) {
            if(num==1) {
                temp+=1;
            }else {
                temp=0;
            }
            maxLong=Math.max(temp,maxLong);
        }
        return maxLong;
    }
}
           
  • JS代码
/**
 * @param {number[]} nums
 * @return {number}
 */
var findMaxConsecutiveOnes = function(nums) {
    let temp=0
    let maxLong=0
    for(let i=0;i<nums.length;i++) {
        if(nums[i]==1) {
            temp+=1;
        }else {
            temp=0;
        }
        maxLong=Math.max(temp,maxLong)
    }
    return maxLong
};

           

2.第三大的树(LeetCode414)

  • 题目概述:给你一个非空数组,返回此数组中 第三大的数 。如果不存在,则返回数组中最大的数。
  • 题目示例:

    输入:[3, 2, 1]

    输出:1

    解释:第三大的数是 1

输入:[1, 2]

输出:2

解释:第三大的数不存在, 所以返回最大的数 2 。

  • 解题思路:这道题看起来很简单,其实有很多需要考虑的情况,有以下几个注意点

    1.在设置初始值时要以MIN_VALUE来设置,下面的第一段代码用的是Long则可以通过,如果用Integer则不会通过,因为测试案例中会有int情况下的最小值,这里还是最好判断一下,所以可以参考一下方法二

    2.注意一定要判断一下数组里的元素是否和目前的前三个值相同

  • java方法一(略微不严谨)
class Solution {
    public int thirdMax(int[] nums) {
        long max1 = Long.MIN_VALUE, max2 = Long.MIN_VALUE, max3 = Long.MIN_VALUE;
        for (int num : nums) {
            if (num == max1 || num == max2 || num == max3) continue;
            if (num > max1) {
                max3 = max2;
                max2 = max1;
                max1 = num;
            } else if (num > max2) {
                max3 = max2;
                max2 = num;
            } else if (num > max3) {
                max3 = num;
            }
        }
        return (int) (max3 == Long.MIN_VALUE ? max1 : max3);
    }
}
           
  • java方法二
class Solution {
    public int thirdMax(int[] nums) {
        int[] arr = new int[]{Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE};
        int count = 0;
        for (int num: nums) {
            if (num == Integer.MIN_VALUE) {
                count++;
            }
            if (num == arr[0] || num == arr[1] || num == arr[2]) {
                continue;
            }
            if (num > arr[0]) {
                arr[2] = arr[1];
                arr[1] = arr[0];
                arr[0] = num;
            } else if (num > arr[1]) {
                arr[2] = arr[1];
                arr[1] = num;
            } else if (num > arr[2]){
                arr[2] = num;
            }
        }
        if (arr[0] == arr[1] || arr[1] == arr[2]) {
            return arr[0];
        }
        if (arr[2] == Integer.MIN_VALUE && count < 1) {
            return arr[0];
        }
        return arr[2];
    }
}