LeetCode - 204 Count Primes & 611 - Valid Triangle Number

LeetCode - 204 Count Primes & 611 - Valid Triangle Number


LeetCode - 204 Count Primes

题目链接
题目大意

筛选0~n([0,n))之间的素数个数。
在这里插入图片描述

解析

如果用经典的判断素数,时间复杂度为O(n*sqrt(n)),会超时。

于是使用经典的埃拉托斯特尼筛法(有动图演示),有关素数也可以看我另一篇博客讲解。

超时:

class Solution {
    //TLE
    public boolean isPrime(int nums){
        if(nums == 0 || nums == 1)
            return false;
        for(int i = 2; i <= (int)Math.sqrt(nums); i++){ // <= not < 
            if(nums%i == 0)
                return false;
        }
        return true;
    }
    
    public int countPrimes(int n) {
        int res = 0;
        for(int i = 0; i < n; i++){
            if(isPrime(i))
                res++;
        }
        return res;
    }
}

正解:

class Solution {
    public int countPrimes(int n) {
        if(n < 3)
            return 0;
        int res = 0;
        boolean[] isPrime = new boolean[n];
        Arrays.fill(isPrime,true);
        isPrime[0] = isPrime[1] = false;
        for(int i = 2; i < n; i++){
            if(isPrime[i]){
                res++;
                for(int j = 2*i; j < n; j+=i) //筛选
                    isPrime[j] = false;
            }
        }
        return res;
    }
}

LeetCode - 611 - Valid Triangle Number

题目链接
题目大意

给定一个包含非负整数的数组,统计其中可以组成三角形三条边的三元组个数。
在这里插入图片描述

解析

很巧妙的方法,使用贪心:

  • 先对数组排序(升序降序都可以,这里按照升序排列);
  • 然后初始化c=num.length - 1b = c-1a = 0,然后如果arr[a] + arr[b] > arr[c],那么所有arr[a ~ b-1]arr[b]arr[c]之间都可以构成三角形,所以可以加上b-a个;
  • 否则说明a小了,就让a++,知道a == b退出;

在这里插入图片描述

class Solution {
    public int triangleNumber(int[] nums) {
        if(nums == null || nums.length < 3)
            return 0;
        int res = 0;
        Arrays.sort(nums);
        for(int c = nums.length-1; c >= 2; c--){
            for(int b = c-1; b >= 1; b--){
                int a = 0;
                while(a < b){
                    if(nums[a] + nums[b] > nums[c]){
                        res += b-a;
                        break;
                    }
                    a++;
                }
            }
        }
        return res;
    }
}
class Solution {
    // more fast
    public int triangleNumber(int[] nums) {
        if(nums == null || nums.length < 3)
            return 0;
        int res = 0;
        Arrays.sort(nums);
        for(int c = nums.length-1; c >= 2; c--){
            int a = 0,b = c-1;
            while(a < b){
                if(nums[a] + nums[b] > nums[c]){
                    res += b-a;
                    b--;
                }else a++;
            }
        }
        return res;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值