20200724:力扣197周周赛上

题目

  1. 好数对的数目
    在这里插入图片描述

  2. 仅含 1 的子串数
    在这里插入图片描述

思路与算法

  1. 第一题直接暴力或者使用map来存值,注意到我们只需要找到这个数字出现的次数num,那么其好数对的个数为排列组合的C(2,N),将其依次存入map并依次计算这个组合数添加入res即可。复杂度可以从暴力的N²降低到到N。
  2. 第二题也是需要仔细看清楚规律,碰到连续的n个1,则添加(n+1)*n/2到res中去即可。注意因为数值较大,需要将各变量都声明为long类型,否则会因为溢出计算错误。

代码实现

  1. 好数对的数目

暴力

class Solution {
    public int numIdenticalPairs(int[] nums) {
        int len = nums.length;
        int count = 0;
        for (int i = 0; i < len - 1; i++) {
            for (int j = i + 1; j < len; j++) {
                if (nums[i] == nums[j]) {
                    count++;
                }
            }
        }
        return count;
    }
}

map

class Solution {
    public int numIdenticalPairs(int[] nums) {
        int res = 0;
        Map<Integer,Integer> map = new HashMap<>();
        for (int num : nums) {
            map.put(num,map.getOrDefault(num,0) + 1);
        }

        for (Map.Entry<Integer,Integer> entryset : map.entrySet()) {
            int val = entryset.getValue();
            res += val * (val - 1) / 2;
        }
        return res;
    }
}
  1. 仅含 1 的子串数
class Solution {
    public int numSub(String s) {
        char[] ch = s.toCharArray();
        long count = 0;
        long res = 0;
        long div = 1000000007;
        for (int i = 0; i < ch.length; i++) {
            char c = ch[i];
            if (c == '0') {
                res += (count * (count + 1) / 2);
                res %= div;
                count = 0;
                
            } else {
                count++;
            }
        }
        res += (count * (count + 1) / 2);
        res %= div;
        return (int) res;
    }
}

复杂度分析

  1. 第一题暴力法为O(N²),map法降低到O(N)
  2. 第二题纯粹的模拟,只需便利一遍,因此为O(N)
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IMMUNIZE

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值