algorithm001 / algorithm

119 stars 152 forks source link

【020-Week01】总结思考 #871

Open lcfgrn opened 5 years ago

lcfgrn commented 5 years ago

链表的总结思考

题目: You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. Example: Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807. 自己写的代码实现: /**

哈希表的总结思考 题目 Given an array of strings, group anagrams together. Example: Input: ["eat", "tea", "tan", "ate", "nat", "bat"], Output: [ ["ate","eat","tea"], ["nat","tan"], ["bat"] ] Note:

自己的实现 class Solution { public List<List> groupAnagrams(String[] strs) { List<List> strLists = new ArrayList<>(); Map<String, List> strMap = new HashMap<>(); for (String str : strs) { int[] arr = new int[26]; for (char ch : str.toCharArray()) { arr[ch - 'a'] ++; } String key = transInts2Str(arr); if (strMap.containsKey(key)) { strMap.get(key).add(str); } else { List strList = new ArrayList<>(); strList.add(str); strMap.put(key, strList); } } for (List strList : strMap.values()) { strLists.add(strList); } return strLists; }

    private String transInts2Str(int[] arr) {
        StringBuffer sb = new StringBuffer();
        for (int i : arr) {
            sb.append(i);
        }
        return sb.toString();
    }

} 别人的实现 class Solution { public List<List> groupAnagrams(String[] strs) { Map<String, List> strMap = new HashMap<>(); for (String str : strs) { char[] chars = str.toCharArray(); Arrays.sort(chars); String key = String.valueOf(chars); strMap.putIfAbsent(key, new ArrayList<>()); strMap.get(key).add(str); } return new ArrayList<>(strMap.values()); } } 总体印象: 1.下面的实现感觉很优雅 本题解题思路: 1.将字符串组中的每个字符串都转换成可以用来比较的key(我采用的是int[26],参考采用的是将字符串中每个字符排序得到新的字符串); 2.使用哈希表,将字符串比较分组,转换为对key的比较分组。