242有效的字母异位词
s
和 t
中每个字符出现的次数相同,则称 s
和 t
互为字母异位词。
创建一个哈希表,把s的每个字符及其个数存储在哈希表中,再比较t的字符及其个数
class Solution {
public boolean isAnagram(String s, String t) {
if (s.length()!=t.length()){
return false;
}
Map<Character, Integer> mapList = new HashMap<>();
for (int i = 0; i < s.length(); i++) {
if (!mapList.containsKey(s.charAt(i))){
mapList.put(s.charAt(i), 1);
}else {
mapList.put(s.charAt(i), mapList.get(s.charAt(i))+1);
}
}
for (int i = 0; i < t.length(); i++) {
if (mapList.containsKey(t.charAt(i))){
mapList.put(t.charAt(i), mapList.get(t.charAt(i))-1);
if (mapList.get(t.charAt(i))<0){
return false;
}
}else {
return false;
}
}
return true;
}
}
349两个数组的交集
解法一:使用哈希表
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Map<Integer, Boolean> mapList = new HashMap<>();
for (int i: nums1) {
if (!mapList.containsKey(i)){
mapList.put(i, false);
}
}
for (int i: nums2) {
if (mapList.containsKey(i)){
mapList.put(i, true);
}
}
int[] result = new int[mapList.size()];
int count = 0;
for (Map.Entry<Integer, Boolean> entry: mapList.entrySet()) {
if (entry.getValue()){
result[count] = entry.getKey();
count++;
}
}
int[] result1 = Arrays.copyOfRange(result, 0, count);
return result1;
}
}
解法二:使用排序加指针
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Arrays.sort(nums1);
Arrays.sort(nums2);
int[] result = new int[nums1.length+1];
result[0] = -1;
int n = 0;
int j=0,i=0;
while (i<nums1.length&&j<nums2.length){
if (nums1[i]==nums2[j]){
if (nums1[i]!=result[n]){
n++;
result[n] = nums1[i];
}
i++;
j++;
}else if(nums1[i]>nums2[j]){
j++;
}else {
i++;
}
}
int[] result1 = Arrays.copyOfRange(result, 1, n+1);
return result1;
}
}
202快乐数
解法一:同142环形链表II 使用快慢指针判断循环
class Solution {
public int cal(int n){
int value = 0;
while(n>0) {
value= value + (n%10) * (n%10);
n = n/10;
}
return value;
}
public boolean isHappy(int n) {
int slow = n, fast = n;
while (slow!=1&&fast!=1){
slow = cal(slow);
fast = cal(fast);
fast = cal(fast);
if(slow==1||fast==1){
return true;
}
if (slow == fast){
return false;
}
}
return true;
}
}
解法二:哈希表判断重复
class Solution {
public boolean isHappy(int n) {
int fast = n, slow = n;
do {
slow = nextInt(slow);
fast = nextInt(nextInt(fast));
if (slow == 1 || fast == 1) {
return true;
}
}while (fast != slow);
return false;
}
public int nextInt(int num){
int sum = 0;
while (num > 0) {
int r = num % 10;
sum += (r * r);
num = num / 10;
}
return sum;
}
}
1两数之和
找出 和为目标值 target
的那 两个 整数,并返回它们的数组下标
建立哈希表,边查找边存储数组元素
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> mapList = new HashMap<>();
int[] result = new int[2];
for (int i = 0; i < nums.length; i++) {
if (mapList.containsKey(target-nums[i])){
result[1] = i;
result[0] = mapList.get(target-nums[i]);
return result;
}else {
mapList.put(nums[i], i);
}
}
return result;
}
}
收获
哈希表可以应用于无序的查找操作,以及值范围较大,无法使用数组进行存储情况的查找操作。
哈希表主要应用于查找,但时间复杂度较高。
相似情况有时可以使用排序算法排序后再查找,从而减少时间复杂度。