(题解)《算法零基础100讲》(第39讲) 非比较排序 - 计数排序

1、 有效的字母异位词(leetcode242

可以建立两个大小为26的整型数组cnt1,cnt2,接着遍历s和t,将里面的字母 - ‘a’ 得到0 - 26 之间的某个数值i(比如a就是0,b就是1),然后cnt1(或2)[i] ++.
cnt中数组的值统计的就是两个字符串中字母的个数。

class Solution {
    public boolean isAnagram(String s, String t) {
        int []cnt = new int[27];
        int []cnt2 = new int[27];
        int len1 = s.length(),len2  = t.length();
        for(int i = 0 ; i < len1 ; i ++)
        {
            cnt[s.charAt(i) - 'a'] ++;
        }
        for(int i = 0 ; i < len2 ; i ++)
        {
            cnt2[t.charAt(i) - 'a'] ++;
        }
        for(int i = 0 ; i < 27 ; i ++)
        {
            if(cnt[i] != cnt2[i])return false;
        }
        return true;
    }
}

2、数组中的第K个最大元素(leetcode215

排序后从后面返回相应的元素。

class Solution {
    public int findKthLargest(int[] nums, int k) {
        Arrays.sort(nums);
        return nums[nums.length  - k];
    }
}

3、丢失的数字(leetcode268

创建一个计数数组cnt,记录出现在nums中的数字,然后进行遍历,返回cnt中数值为0的下标就可以了

class Solution {
    public int missingNumber(int[] nums) {
        int n = nums.length;
        int []cnt = new int[n + 1];
        for(int i = 0 ; i < n ; i ++ )cnt[nums[i]] ++;
        for(int i = 0 ; i <= n ; i ++)if(cnt[i] == 0)return i;
        return 0;
    }
}

4、找不同(leetcode389

使用两个计数数组大小为26的cnt,分别记录对应字符串的字符数量,然后for循环遍历对比;

class Solution {
 public char findTheDifference(String s, String t) {
        int len1 = s.length(), len2 = t.length();
        int []cnt1 = new int [27];
        int []cnt2 = new int [27];
        for(int i = 0 ; i < len1 ; i ++)cnt1[s.charAt(i) - 'a'] ++;
        for(int i = 0 ; i < len2 ; i ++)cnt2[t.charAt(i) - 'a'] ++;
        for(int i = 0 ; i < 27 ; i ++)if(cnt1[i] != cnt2[i])
        {
            int res = 'a' + i;
            return (char)res;
        }
        return '0';
    }
}

5、错误的集合(leetcode645

和前面几题同样的做法,计数器数组cnt

class Solution {
    public int[] findErrorNums(int[] nums) {
        int n = nums.length;
        int []cnt = new int [n + 2];
        for(int i = 0 ; i < n ; i ++)
        {
            cnt[nums[i]] ++;
        }
        int []res = new int [2];
        for(int i = 1 ; i <= n ; i ++ )
        {
            if(cnt[i] == 2)
            {
                res[0] = i;
            }
            if(cnt[i] == 0)res[1] = i;
        }
        return res;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值