1.查找共用字符
思路:
1.先统计第一个字符串中字符的数量
2.然后统计除第一个字符串中字符的数量,并且与第一个字符串相比较,取最小值。
3.倘若值不为0,则输出该字符,说明该字符就是公用字符.
class Solution {
public List<String> commonChars(String[] words) {
List<String> ans = new ArrayList<>();
int[] hash =new int[26];//用来记录每个字符的出现次数
if(words.length==0) return ans;
//统计第一个字符串中的字符数量
for(int i =0;i<words[0].length();i++){
hash[words[0].charAt(i)-'a']+=1;
}
//统计其他字符串中的字母数量
for(int i =1;i<words.length;i++){
int[] otherHash = new int[26];//只在内部更新,不能作为全局变量
for(int j =0;j<words[i].length();j++){
otherHash[words[i].charAt(j)-'a']++;
}
//更新共用字符
for(int k=0;k<26;k++){
hash[k]=Math.min(hash[k],otherHash[k]);
}
}
//输出
for(int i =0;i<26;i++){
while(hash[i]!=0){
char c =(char) (i+'a');//需要进行强转
ans.add(String.valueOf(c));
hash[i]--;//输出后数量减一
}
}
return ans;
}
}
2.两个数组的交集
思路:
1.先统计第一个数组的元素。
2.再创建一个新的哈希set,与第一个数组中的元素比较,如果第一个数组中包含第二个素组中的元素,则打印。
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
if(nums1.length==0||nums2.length==0) return new int[0];
Set<Integer> ans = new HashSet<>();//用来输出答案
Set<Integer> set = new HashSet<>();//用来暂时存储数据
//遍历第一个数组
for(int i:nums1){
set.add(i);
}
//遍历第二个数组,并且与第一个数组比较
for(int i :nums2){
if(set.contains(i)){//有相同元素
ans.add(i);
}
}
//输出
int[] ansArr = new int[ans.size()];//创建一个数组,用于输出
//将set的值放入int中
int index =0;
for(int i:ans){
ansArr[index] = i;
index++;
}
return ansArr;
}
}
3.两个数组的交集 II
思路:同上(使用List)
只需要将比较后的元素去除即可
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
if(nums1.length==0||nums2.length==0) return new int[0];
List<Integer> list = new ArrayList<>();
List<Integer> ans = new ArrayList<>();//用于输出答案
//遍历第一个数组,且放入listt中
for(int i:nums1){
list.add(i);
}
//遍历第二个数组,且与第一个数组比较
for(int i:nums2){
if(list.contains(i)){
ans.add(i);
//从list中去除已经匹配的数值
list.remove(Integer.valueOf(i));
}
}
//输出
int [] ansArr =new int[ans.size()];
int index =0;
for(int i:ans){
ansArr[index++]=i;
}
return ansArr;
}
}
思路2:数组排序值,小的先动
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
Arrays.sort(nums1);//排序
Arrays.sort(nums2);
List<Integer> ans = new ArrayList<>();
for(int i=0,j=0;i<nums1.length&&j<nums2.length;){
if(nums1[i]<nums2[j]){//小的先动
i++;
}
else if(nums1[i]>nums2[j]){//小的先动
j++;
}else{
ans.add(nums2[j]);
i++;
j++;
}
}
//输出
int[] ansArr =new int[ans.size()];
int index =0;
for(int i:ans){
ansArr[index++]=i;
}
return ansArr;
}
}
4.快乐数
思路:
1.本题利用了set中元素不重复的思想
2.一旦新数与set中数重复,说明不是快乐数
3.无限循环的理解:在本题中就是set中的数与新产生的数重复
class Solution {
public boolean isHappy(int n) {
Set<Integer> set = new HashSet<>();//set值不能重复
while(n!=1&&!set.contains(n)){//n不等于1且n不重复
set.add(n);//把n放入set中
n=getNexNum(n);//更新n的值
}
return n==1;//此时为快乐数
}
//取n每一位的值平方和
private int getNexNum(int n){
int res =0;
while(n!=0){
int x =n%10;//取余
res+=x*x;
n /=10;//取商,更新n的值
}
return res;
}
}