leetcode 热题100道Day03

66 阅读1分钟

leetcode 热题100道Day03

有效的字母异位词

* 242.有效的字母异位词 字典接法
* 时间复杂读o(m+n), 空间复杂度o(1)

    public static boolean  isAnagram(String s, String t){
            int[] record = new int[26];

            for (int i = 0;i < s.length();i++){
                record[s.charAt(i)-'a']++;
                System.out.println(s.charAt(i)-'a');
                System.out.println('a');
            }
            for (int i = 0; i<t.length();i++){
                record[t.charAt(i)-'a']--;
            }
        for (int i : record) {
            if (i != 0){
                return false;
            }
        }
        return true;
    }

字母异位词分组


public class 字母异位词分组 {
    public static void main(String[] args) {
        String[] strings = {"eat","tea","tan","ate","nat","bat"};
        graupAnagrams(strings);
    }
    public static List<List<String>> graupAnagrams(String[] strs){
        HashMap<String, ArrayList<String>> map = new HashMap<>();
        ArrayList<Object> res = new ArrayList<>();
        int cnt = 0;
        for (String str : strs) {
//            System.out.println(str);
            char[] chars = str.toCharArray();
            System.out.println(chars);
            Arrays.sort(chars);
            System.out.println(chars);
            String nstr = new String(chars);
            if (!map.containsKey(nstr)){
                map.put(nstr,new ArrayList<>());
            }
            map.get(nstr).add(str);
            
        }
        return new ArrayList<>(map.values());
    }
}

排序链表

class Solution {
    public ListNode sortList(ListNode head) {
        return mergeSort(head);
    }

    // 归并排序
    private ListNode mergeSort(ListNode head){
        // 如果没有结点/只有一个结点,无需排序,直接返回
        if (head==null||head.next==null) return head;
        // 快慢指针找出中位点
        ListNode slowp=head,fastp=head.next.next,l,r;
        while (fastp!=null&&fastp.next!=null){
            slowp=slowp.next;
            fastp=fastp.next.next;
        }
        // 对右半部分进行归并排序
        r=mergeSort(slowp.next);
        // 链表判断结束的标志:末尾节点.next==null
        slowp.next=null;
        // 对左半部分进行归并排序
        l=mergeSort(head);
        return mergeList(l,r);
    }
    // 合并链表
    private ListNode mergeList(ListNode l,ListNode r){
        // 临时头节点
        ListNode tmpHead=new ListNode(-1);
        ListNode p=tmpHead;
        while (l!=null&&r!=null){
            if (l.val<r.val){
                p.next=l;
                l=l.next;
            }else {
                p.next=r;
                r=r.next;
            }
            p=p.next;
        }
        p.next=l==null?r:l;
        return tmpHead.next;
    }
}