1 217. 存在重复元素

给定一个整数数组,判断是否存在重复元素。
如果任意一值在数组中出现至少两次,函数返回 true 。如果数组中每个元素都不相同,则返回 false

示例 1:
输入: [1,2,3,1]
输出: true
示例 2:
输入: [1,2,3,4]
输出: false

  1. class Solution {
  2. public boolean containsDuplicate(int[] nums) {
  3. Set s = new HashSet();
  4. for(int i: nums){
  5. if(s.contains(i)){
  6. return true;
  7. }
  8. s.add(i);
  9. }
  10. return false;
  11. }
  12. }

2 219. 存在重复元素 II

给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i j,使得 nums [i] = nums [j],并且 ij 的差的 绝对值 至多为 k

示例 1:
输入: nums = [1,2,3,1], k = 3
输出: true
示例 2:
输入: nums = [1,0,1,1], k = _1
输出: true
示例 3:
输入: nums = [1,2,3,1,2,3], k
= _2
输出: false

class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        Set<Integer> set = new HashSet();

        for(int i = 0; i< nums.length;  i++){
            if(set.contains(nums[i]))  return true;
            set.add(nums[i]);
            if(set.size()>k){
                set.remove(nums[i-k]);
            }   
    }
    return false;
}}

3 387. 字符串中的第一个唯一字符

难度简单
给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。
案例:
s = “leetcode”
返回 0.
s = “loveleetcode”,
返回 2.

class Solution {
    public int firstUniqChar(String s) {
        HashMap<Character, Integer> count = new HashMap<Character, Integer>();
        int n = s.length();
        // build hash map : character and how often it appears
        for (int i = 0; i < n; i++) {
            char c = s.charAt(i);
            count.put(c, count.getOrDefault(c, 0) + 1);
        }

        // find the index
        for (int i = 0; i < n; i++) {
            if (count.get(s.charAt(i)) == 1) 
                return i;
        }
        return -1;
    }
}
  • getOrDefault(key, value) value 为给定默认值;
  • 如果key 的值为null 返回默认值; 不然返回查询到的值
    getOrDefault(Character c, int v){
      if(map.get(c ) == null) return v;
      return map.get(c);
    }
    

4 389. 找不同

难度简单
给定两个字符串 st,它们只包含小写字母。
字符串 t 由字符串 s 随机重排,然后在随机位置添加一个字母。
请找出在 t 中被添加的字母。

示例:
输入:
s = “abcd”
t = “abcde”
输出:e

class Solution {
    public char findTheDifference(String s, String t) {
        char n = 0;
        for(int i = 0; i<s.length();i++){

                 n ^= t.charAt(i) ^  s.charAt(i);


        }
         n ^= t.charAt(t.length()-1);
        return n;

    }
}

类型题

  • 数组中只出现一次的数; 数组中只出现两次的数;
  • 方法 异或运算

5 49. 字母异位词分组

难度中等
给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。
示例:
输入: ["eat", "tea", "tan", "ate", "nat", "bat"]
输出:
[
[“ate”,”eat”,”tea”],
[“nat”,”tan”],
[“bat”]
]

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        if (strs.length == 0) return new ArrayList();
        Map<String, List> ans = new HashMap<>();
        for(String s: strs){
            char[] ca = s.toCharArray();

            Arrays.sort(ca);
            String key = String.valueOf(ca);
            if(!ans.containsKey(key)) ans.put(key, new ArrayList());
            ans.get(key).add(s);
        }
        return new ArrayList(ans.values());
    }
}
  • 把字符串转成数组
  • 数组排序
  • 数组转成字符串
  • 把转好的字符串作为Key, 与Map中的key对比