题目1:【二刷完成】
代码1:
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 i=0; i<record.length; i++){
if (record[i] != 0){
return false;
}
}
/*
for (int count: record){
if (count != 0){
return false;
}
}
*/
return true;
}
}
题目2:【二刷完成】
代码2:
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<>();
Set<Integer> set2 = new HashSet<>();
for (int i : nums1){
set1.add(i);
}
for (int j : nums2){
if (set1.contains(j)){
set2.add(j);
}
}
int[] intArray = set2.stream().mapToInt(Integer::intValue).toArray();
return intArray;
}
}
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
//set方法
if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {
return new int[0];
}
Set<Integer> set1 = new HashSet<>();
Set<Integer> set2 = new HashSet<>();
for (int i: nums1){
set1.add(i);
}
for (int i : nums2){
if (set1.contains(i)){
set2.add(i);
}
}
//此时set2中存放的是共同的元素
//现在将set转换从数组
int[] array = new int[set2.size()];
int j = 0;
for (int i : set2){
array[j++] = i;
}
return array;
/*
将结果集合转为数组
return resSet.stream().mapToInt(x -> x).toArray();
*/
}
}
题目3:【二刷完成】
代码3:
class Solution {
public boolean isHappy(int n) {
//record是来记录判断这个过程的数字
Set<Integer> record = new HashSet<>();
//n=1符合条件,n在record里面的也不用再判断,因为会一直循环
//所以将两个条件结合起来的最好
while(n != 1 && !record.contains(n)){
record.add(n);
n = nextNum(n);
}
return n == 1;
}
//先计算输入n输出的数字
private int nextNum(int n){
int temp = 0;
int sum = 0;
while(n != 0){
temp = n % 10;
sum += temp*temp;
n = n / 10;
}
return sum;//返回下一个的n值
}
}
题目4:【二刷完成】
代码4:
class Solution {
public int[] twoSum(int[] nums, int target) {
//暴力解法
int sum = 0;
int[] array = new int[2];
for (int i=0; i<nums.length; i++){
sum = nums[i];
for (int j=i+1; j<nums.length; j++){
sum += nums[j];
if (sum == target){
array[0] = i;
array[1] = j;
return array;
}else{
sum = nums[i];
}
}
}
return null;
}
}
class Solution {
public int[] twoSum(int[] nums, int target) {
//使用map方法解决
int[] record = new int[2];
if (nums==null || nums.length==0){
return record;
}
Map<Integer, Integer> map = new HashMap<>();
for (int i=0; i<nums.length; i++){
int temp = target - nums[i];
if (map.containsKey(temp)){
record[1] = i;
record[0] = map.get(temp);
break;
}
map.put(nums[i],i);
}
return record;
}
}