242
class Solution {
public boolean isAnagram(String s, String t) {
int[] hash = new int[26];
for(int i = 0;i < s.length();i++){
hash[s.charAt(i) - 'a']++;
}
for(int j = 0;j < t.length(); j++){
hash[t.charAt(j) - 'a']--;
}
for(int k = 0; k< hash.length; k++){
if(hash[k]!=0){
return false;
}
}
return true;
}
}
总结:java的数组length是属性,String字符串length()是方法,charAt()方法取某个位置上的字符。Java申请数组会默认初始化为0.
349
import java.util.HashSet;
import java.util.Set;
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {
return null;
}
HashSet<Integer> set1 = new HashSet<Integer>();
HashSet<Integer> resSet = new HashSet<Integer>();
for(int i: nums1){
set1.add(i);
}
for(int i: nums2){
if(set1.contains(i)){
resSet.add(i);
}
}
return resSet.stream().mapToInt(x -> x).toArray();
}
}
总结:add()方法把元素添加进集合里,contains()查找集合里是否有目标元素,有返回TRUE。
202
class Solution {
public boolean isHappy(int n) {
Set<Integer> record = new HashSet<Integer>();
while( n != 1 && !record.contains(n)){
record.add(n);
n = getNextNumber(n);
}
return n == 1;
}
private int getNextNumber(int n){
int res = 0;
while(n >0){
int temp = n % 10;
res += temp *temp;
n = n/10;
}
return res;
}
}
总结: 学到了可以用循环取每个位的数值。
1
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;
}
}
需要学习一下Java的自带的数据结构