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;
}
}