一、217存在重复元素
1.题目
https://leetcode-cn.com/problems/contains-duplicate/
给定一个整数数组,判断是否存在重复元素。
如果存在一值在数组中出现至少两次,函数返回 true 。如果数组中每个元素都不相同,则返回 false 。
2.思路
用哈希表,key存储数值,value存储出现的次数
3.代码
class Solution {
public boolean containsDuplicate(int[] nums) {
if (nums.length <= 1 ) return false;
Map<Integer,Integer> map = new HashMap<>();
//int value;
for(int i =0; i<nums.length; i++){
if(map.containsKey(nums[i])){
return true;
}else{
map.put(nums[i],1);
}
}
return false;
}
}
二、389. 找不同
1.题目
给定两个字符串 s 和 t,它们只包含小写字母。
字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。
请找出在 t 中被添加的字母。
https://leetcode-cn.com/classic/problems/find-the-difference/description/
2.思路
首先遍历字符串 ss,对其中的每个字符都将计数值加 11;然后遍历字符串 tt,对其中的每个字符都将计数值减 11。当发现某个字符计数值为负数时,说明该字符在字符串 tt 中出现的次数大于在字符串 ss 中出现的次数,因此该字符为被添加的字符。
3.代码
class Solution {
public char findTheDifference(String s, String t) {
//base case
if (s.length() == 0 && t.length() == 0) return ' ';
int [] count = new int [26];
for (int i =0; i<s.length();i++){
char num1 = s.charAt(i);
count[num1 - 'a'] ++;
}
for (int j =0; j<t.length(); j++){
char num2 = t.charAt(j);
count[num2 - 'a']--;
if (count[num2 -'a'] <0){
return num2;
}
}
return ' ';
}
}