class Solution {
public boolean isAnagram(String s, String t) {
int[] record = new int[26];
for(int i = 0; i < s.length(); i++){
record[s.charAt(i) - 'a']++;
}
for(int i = 0; i < t.length(); i++){
record[t.charAt(i) - 'a']--;
}
for(int count: record){
if(count != 0){// record数组如果有的元素不为零0,说明字符串s和t 一定是谁多了字符或者谁少了字符。
return false;
}
}
return true;
}
}
思路:
-
遍历字符串
s
的每一个字符,对应的record
数组中的位置增加1。这样,遍历完s
后,record
数组中的每个位置的值就表示了该位置对应的字符在s
中出现的次数。 -
接着遍历字符串
t
的每一个字符,对应的record
数组中的位置减少1。这样,遍历完t
后,如果s
和t
是字母异位词,那么record
数组中的所有值都应该是0。
class Solution {
public int[] intersection(int[] nums1, int[] nums2){
if(nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0){
return new int[0];
}
Set<Integer> set1 = new HashSet<>();
Set<Integer> reset = new HashSet<>();
for(int i: nums1){
set1.add(i);
}
for(int j: nums2){
if(set1.contains(j)){
reset.add(j);
}
}
return reset.stream().mapToInt(x -> x).toArray();//将结果集合转为数组
}
}
思路:
-
首先进行基本的空值和长度为0的检查。如果其中一个数组为空或长度为0,则直接返回一个空数组。
-
使用两个哈希集合,
set1
用于存储nums1
的所有不同的元素,而reset
用于存储结果。 -
遍历
nums1
的每一个元素并将其添加到set1
中。因为哈希集合不允许重复的元素,所以即使nums1
中有重复的元素,set1
中也只会有一个。 -
接着遍历
nums2
的每一个元素。对于nums2
中的每一个元素,如果它在set1
中存在,那么就将其添加到reset
中。 -
最后,将结果集合
reset
转换为数组并返回。
class Solution {
public boolean isHappy(int n) {
Set<Integer> record = new HashSet<>();
while(n!=1 && !record.contains(n)){
record.add(n);
n = getNextNumber(n);
}
return n==1;
}
public int getNextNumber(int n){
int res = 0;
while(n>0){
int temp = n % 10;
res += temp * temp;
n = n / 10;
}
return res;
}
}
思路:
- 循环终止的条件是
n
变为 1 或者n
已经在record
中出现过(这意味着我们已经进入了一个循环,并且n
永远不会变为 1)。 - 如果最后
n
为 1,返回true
;否则返回false
。 -
用了一个
while
循环来处理数字的每一位。循环的条件是n > 0
,这确保我们处理完数字的每一位。 -
int temp = n % 10;
:我们使用模运算来获取n
的最后一位。例如,82 % 10 = 2。 -
res += temp * temp;
:我们计算这一位的平方,然后加到res
上。这实现了累加每一位的平方的功能。 -
n = n / 10;
:我们使用整数除法来去除n
的最后一位,以便在下一次迭代中处理下一个数字。例如,82 / 10 = 8。
class Solution {
public int[] twoSum(int[] nums, int target) {
int [] res= new int[2];
if(nums == null || nums.length == 0){
return res;
}
Map<Integer,Integer> map = new HashMap<>();
for(int i=0; i < nums.length; i++){
int temp = target - nums[i];
if(map.containsKey(temp)){
res[1] = i;
res[0] = map.get(temp);
break;
}
map.put(nums[i],i);
}
return res;
}
}
思路:
1. int temp = target - nums[i];
:计算目标值减去当前数字的差值。
2. if(map.containsKey(temp))
:检查这个差值是否在哈希表中。如果是,说明我们找到了两个数字的和为目标值,然后保存这两个数字的索引并退出循环。
3. map.put(nums[i],i);
:如果没有找到,我们将当前数字及其索引放入哈希表。