1.力扣热题100

文章目录

  • 一、两数之和
  • 二、字母异位词分组
  • 三、最长连续序列

一、两数之和

public int[] twoSum(int[] nums, int target) {
        HashMap<Integer, Integer> numIndexMap = new HashMap();
        int[] result = new int[2];
        for(int i = 0;i < nums.length;i ++){
            if(numIndexMap.containsKey(target - nums[i])){
                result[0] = i;
                result[1] = numIndexMap.get(target - nums[i]);
            }
            numIndexMap.put(nums[i], i);
        }
        return result;
}

用空间换时间,使时间复杂度降到 O(N)

二、字母异位词分组

public List<List<String>> groupAnagrams(String[] strs) {
         Map<String, List<String>> strListMap = new HashMap<>();
         for (String str : strs){
             char[] charArray = str.toCharArray();
             Arrays.sort(charArray);
             String key = new String(charArray);
             List<String> curList = strListMap.getOrDefault(key, new ArrayList<>());
             curList.add(str);
             strListMap.put(key, curList);
         }
         return new ArrayList<>(strListMap.values());
    }
}

将字符串转为字符数组,利用Arrays.sort()实现字符串排序

三、最长连续序列

你可能感兴趣的:(刷题,leetcode,力扣热题100)