Showing posts with label LeetCode. Show all posts
Showing posts with label LeetCode. Show all posts

Thursday, June 15, 2017

116. Populating Next Right Pointers in Each Node

三刷 06/2022
Version #1 BFS
看了题目的constraint,要求O(1) extra space,所以这个方法是不可行的
Time O(N)
Space O(N)
Runtime: 3 ms, faster than 44.31% of Java online submissions for Populating Next Right Pointers in Each Node.
Memory Usage: 48.2 MB, less than 10.30% of Java online submissions for Populating Next Right Pointers in Each Node.

class Solution {
    public Node connect(Node root) {
        if (root == null) {
            return null;
        }
        Queue<Node> que = new ArrayDeque<>();
        que.offer(root);
        while (!que.isEmpty()) {
            int size = que.size();
            Node prev = null;
            while (size-- > 0) {
                Node curr = que.poll();
                if (prev != null) {
                    prev.next = curr;
                }
                if (curr.left != null) {
                    que.offer(curr.left);
                }
                if (curr.right != null) {
                    que.offer(curr.right);
                }
                prev = curr;
            }
        }
        return root;
    }
}

Version #2 Add hoc method with constant space

Runtime: 0 ms, faster than 100.00% of Java online submissions for Populating Next Right Pointers in Each Node.
Memory Usage: 47.1 MB, less than 62.18% of Java online submissions for Populating Next Right Pointers in Each Node.

Time O(N)
Space O(1)
class Solution {
    public Node connect(Node root) {
        // Maitain a head node as the left most node of each level
        Node head = root;
        while (head != null) {
            Node curr = head;
            if (curr.left == null) {
                break;
            }
            while (curr != null) {
                // Reach the leaf of the tree
                curr.left.next = curr.right;
                if (curr.next != null) {
                    curr.right.next = curr.next.left;
                }
                curr =  curr.next;
            }
            head = head.left;
        }
        return root;
    }
}


Version #1 套用level order traversal 模板
Time O(n)
Space O(n)

一刷
写High了忘了加left和right children
非常需要注意
18.95 %
public class Solution {
    public void connect(TreeLinkNode root) {
        if (root == null) return;
        TreeLinkNode prev = null;
        TreeLinkNode curr;
        int size;
        Queue<TreeLinkNode> que = new LinkedList<>();
        que.offer(root);
       
        while (!que.isEmpty()) {
            size = que.size();
            while (size-- > 0) {
                curr = que.poll();
                if (prev != null) {
                    prev.next = curr;
                }
                prev = curr;
                if (curr.left != null) que.offer(curr.left);
                if (curr.right != null) que.offer(curr.right);
            }
            prev.next = null;
            prev = null;
        }
    }
}

二刷

Runtime: 1 ms, faster than 57.79% of Java online submissions for Populating Next Right Pointers in Each Node.
Memory Usage: 39.1 MB, less than 70.19% of Java online submissions for Populating Next Right Pointers in Each Node.
class Solution {
    public Node connect(Node root) {
        //  a
        //  /\
        // b -> c -> NULL
        if (root == null) {
            return root;
        }
        Queue<Node> que = new LinkedList<>();
        que.offer(root);
        while (!que.isEmpty()) {
            int size = que.size();
            Node prev = null;
            while (size-- > 0) {
                Node curr = que.poll();
                if (prev != null) {
                    prev.next = curr;
                }
                if (curr.left != null) {
                    que.offer(curr.left);
                    que.offer(curr.right);
                }
                prev = curr;
            }       
        }
        return root;
    }
}

Version #2 Better solution
看了LC上答案,可以不用queue,做到O(1)space

Runtime: 0 ms, faster than 100.00% of Java online submissions for Populating Next Right Pointers in Each Node.
Memory Usage: 38.5 MB, less than 99.89% of Java online submissions for Populating Next Right Pointers in Each Node.

class Solution {
    public Node connect(Node root) {
        //      a -> NULL
        //      /\
        //     b -> c -> NULL
        //    /\    /\
        //   d->e->f->g-> NULL
        Node curr = root;
        while (curr != null) {
            Node head = curr;
            while (curr != null) {
                if (curr.left != null) {
                    curr.left.next = curr.right;
                }
                if (curr.right != null && curr.next != null) {
                    curr.right.next = curr.next.left;
                }
                curr = curr.next;
            }
            curr = head.left;
        }
        return root;
    }
}

Friday, June 9, 2017

215. Kth Largest Element in an Array

五刷
Version #1 Quick Selection
Runtime: 1 ms, faster than 99.54% of Java online submissions for Kth Largest Element in an Array.
Memory Usage: 44.9 MB, less than 34.28% of Java online submissions for Kth Largest Element in an Array.
class Solution {
    public int findKthLargest(int[] nums, int k) {
        // select a num as pivot
        // partition the array so that all elements to the pivot left are larger than or equals to it, all the elements to the pivot right are smaller than or equals to it
        // if pivot is the kth element, return pivot
        // else if pivot index is larger than k, start partitioning from the pivot's left
        // else start partitioning from the pivot's right
        if (nums == null || nums.length < k) {
            throw new IllegalArgumentException();
        }
        k--;
        int start = 0, end = nums.length - 1;
        while (start < end) {
            int n = partition(nums, start, end);
            if (n == k) {
                return nums[n];
            } else if (n < k) {
                start = n + 1;
            } else {
                end = n - 1;
            }
        }
        return nums[k];
    }
    
    // partition the array between start and left
    // return the index of the pivot number
    //  0 1 2 3 4 5 6 7 8 middle = 4
    //  s               e pivot = nums[4] = 2
    //              r l
    // [5,6,3,5,3,4,2,1,2]
    private int partition(int[] nums, int start, int end) {
        int middle = start + (end - start) / 2;
        int pivot = nums[middle];
        swap(nums, middle, start);
        int left = start + 1, right = end;
        while (left <= right) {
            while (left <= right && nums[left] > pivot) {
                left++;
            }
            while (left <= right && nums[right] < pivot) {
                right--;
            }
            if (left <= right) {
                // swap
                int temp = nums[left];
                nums[left] = nums[right];
                nums[right] = temp;
                left++;
                right--;
            }
        }
        swap(nums, start, right);
        return right;
    }
    private void swap(int[] nums, int i, int j) {
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}

四刷

99.98 %
class Solution {
    public int findKthLargest(int[] nums, int k) {
        if (nums == null || nums.length < k) {
            return 0;
        }
        // Randomly pick up a number, split the nums into 2 parts
        //         index
        // <= num, num, >= num
        // if index of num is larger than k, find k from [0,indexNum)
        // if smaller than k, find k-(index+1) from (indexNum, len)
        int start = 0;
        int end = nums.length - 1;
        Random rd = new Random();
        int target = k;
        //r sl              e
        // [6,2,3,1,2,4,5,5,3]
        while (start < end) {
            int curr = start + rd.nextInt(end - start + 1);
            swap(nums, curr, end);
            int left = start;
            int right = end - 1;
            while (left <= right) {
                while (left <= right && nums[left] > nums[end]) {
                    left++;
                }
                while (left <= right && nums[right] < nums[end]) {
                    right--;
                }
                if (left <= right) {
                    swap(nums, left, right);
                    left++;
                    right--;
                }
            }
            swap(nums, left, end);
            if (left - start + 1 == target) { // target = 3
                return nums[left];
            } else if (left - start + 1 > target) {
                end = left - 1;
            } else {
                target = target - (left - start + 1);
                start = left + 1;
            }
        }
        return nums[start];
     
    }
    private void swap(int[] nums, int x, int y) {
        int temp = nums[x];
        nums[x] = nums[y];
        nums[y] = temp;
    }
}


三刷
 97.65 %
class Solution {
    public int findKthLargest(int[] nums, int k) {
        if (nums == null || nums.length == 0 || k > nums.length) {
            return -1;
        }
        int start = 0;
        int end = nums.length - 1;
        while (start <= end) {
            int pivotIndex = start + new Random().nextInt(end - start + 1);
            int index = partition(nums, start, end, pivotIndex);
            if (index == k - 1) {
                return nums[index];
            }
            if (index > k - 1) {
                end = index - 1;
            } else {
                start = index + 1;
            }
        }
        return nums[start];
    }
 
    private int partition(int[] nums, int start, int end, int pivotIndex) {
        // Partition the subarray [start, end] and return the index of pivot
        int pivot = nums[pivotIndex];
        swap(nums, pivotIndex, end);
        int left = start;
        int right = end - 1;
        while (left <= right) {
            while (left <= right && nums[left] > pivot) {
                left++;
            }
            while (left <= right && nums[right] <= pivot) {
                right--;
            }
            if (left <= right) {
                swap(nums, left, right);
                left++;
                right--;
            }
        }
        swap(nums, end, left);
        return left;
    }
 
    private void swap(int[] nums, int i, int j) {
        if (i == j) {
            return;
        }
        int temp = nums[i];
        nums[i] = nums[j];
        nums[j] = temp;
    }
}

二刷
Random quick select
72.91 %

class Solution {
    public int findKthLargest(int[] nums, int k) {
        // QuickSelect
        if (nums == null || nums.length == 0) throw new IllegalArgumentException();
        int start = 0;
        int end = nums.length - 1;
        Random rd = new Random();
        // [start, end]
        while (start <= end) {
            int random = start + rd.nextInt(end - start + 1);
            int index = partition(nums, start, end, random);
         
            if (index + 1 == k) return nums[index];
            else if (index < k) {
                start = index + 1;
            } else {
                end = index - 1;
            }
        }
        return nums[end];
     
    }
    // given a pivot in subarray[start, end]-> find the index of pivot in the array
    private int partition(int[] nums, int start, int end, int random) {
     
        int pivot = nums[random];
        nums[random] = nums[end];
        nums[end] = pivot;
        int left = start;
        int right = end - 1;
 
        while (left <= right) {
            while (left <= right && nums[left] > pivot) left++;
            while (left <= right && nums[right] < pivot) right--;
            if (left <= right) {
                int temp = nums[left];
                nums[left] = nums[right];
                nums[right] = temp;
                left++;
                right--;
            } 
        }
     
        nums[end] = nums[left];
        nums[left] = pivot;
        return left;
    }
}

这个总结很神
https://leetcode.com/problems/kth-largest-element-in-an-array/#/solutions
67.27 %

Version #1 MinHeap

  • 最好不要命名为pq,用minHeap

public class Solution {
    public int findKthLargest(int[] nums, int k) {
        if (nums == null || nums.length == 0 || k <= 0 || nums.length < k) throw new IllegalArgumentException();
        //min heap
        PriorityQueue<Integer> pq = new PriorityQueue<>(k);
        for (int i = 0; i < nums.length; i++) {
            if (pq.size() < k) {
                pq.offer(nums[i]);
            } else {
                if (nums[i] > pq.peek()) {
                    pq.poll();
                    pq.offer(nums[i]);
                }
            }
        }
        return pq.peek();
    }
}

Version #2 Quick Selection
二刷
94.62 %

public class Solution {
    public int findKthLargest(int[] nums, int k) {
        if (nums == null || k > nums.length) return -1;
        //TODO
        return quickSelect(nums, 0, nums.length - 1, k);
    }
    private int quickSelect(int[] nums, int start, int end, int k) {
        if (start >= end) return nums[end];
        int left = start;
        int right = end;
        int pivot = nums[(left + right) / 2];
        while (left <= right) {
            while (left <= right && nums[left] > pivot) left++;
            while (left <= right && nums[right] < pivot) right--;
            if (left <= right) {
                int temp = nums[left];
                nums[left] = nums[right];
                nums[right] = temp;
                left++;
                right--;
            }
        }
        //find the kth->find the index = start + k - 1
        if (start + k - 1 <= right) {
            return quickSelect(nums, start, right, k);
        } else if (start + k - 1 >= left) {
            return quickSelect(nums, left, end, k - (left - start));
        } else {
            return nums[right + 1];
        }
     
    }
}

Another version
98.80 %
这里非常容易出错,如果内部不用while的话,需要保证所有的分支都是互斥的
这样保证每测试一次left <= right,两个指针都只移动一次
不然就会出错

while (left <= right) {
            if (nums[left] > pivot) left++;
            else if (nums[right] < pivot) right--;
            else {
                int temp = nums[left];
                nums[left] = nums[right];
                nums[right] = temp;
                left++;
                right--;
            }
        }

一刷

class Solution {
    /*
     * @param k : description of k
     * @param nums : array of nums
     * @return: description of return
     */
    public int kthLargestElement(int k, int[] nums) {
        // write your code here
        if (nums == null || nums.length == 0) {
            return -1;
        }
        return quickSelect(nums, 0, nums.length - 1, k);
    }
    private int quickSelect(int[] nums, int start, int end, int k) {
        if (start >= end) {
            return nums[start];
        }
   
        int left = start;
        int right = end;
        int pivot = nums[(left + right) / 2];
        while (left <= right) {
            while (left <= right && nums[left] > pivot) {
                left++;
            }
            while (left <= right && nums[right] < pivot) {
                right--;
            }
            if (left <= right) {
                int temp = nums[left];
                nums[left] = nums[right];
                nums[right] = temp;
                left++;
                right--;
            }
        }
        if (start + k - 1 <= right) {
            return quickSelect(nums, start, right, k);
        } else if (start + k - 1 >= left) {
            return quickSelect(nums, left, end, k - (left - start));
        } else return nums[right + 1];
    }
}

Tuesday, April 18, 2017

295. Find Median from Data Stream

四刷 06/2022
Version #1 Two Heaps
一开始写了一个bug就是无脑向maxHeap里面offer然后再balance
这样会造成很小的值被balance到larger half的minHeap里面
需要先和两个heap的peek value比较之后再往里面塞

Time - addNum O(logN), findMedian O(1)
Space - O(N)
Runtime: 183 ms, faster than 50.19% of Java online submissions for Find Median from Data Stream.
Memory Usage: 125.3 MB, less than 34.18% of Java online submissions for Find Median from Data Stream.
class MedianFinder {
    Queue<Integer> minHeap;
    Queue<Integer> maxHeap;
    public MedianFinder() {
        minHeap = new PriorityQueue<>();
        maxHeap = new PriorityQueue<>(Collections.reverseOrder());
    }
    
    public void addNum(int num) {
        // maxHeap contains smaller half of numbers
        // minHeap contains larger half of numbers
        // maxHeap.size() == minHeap.size()
        // or maxHeap.size() == minHeap.size() + 1;
        if (maxHeap.isEmpty() || num <= maxHeap.peek()) {
            maxHeap.offer(num);
        } else {
            minHeap.offer(num);
        }
        if (maxHeap.size() < minHeap.size()) {
            maxHeap.offer(minHeap.poll());
        }
        if (maxHeap.size() > minHeap.size() + 1) {
            minHeap.offer(maxHeap.poll());
        }
    }
    
    public double findMedian() {
        if (maxHeap.size() == minHeap.size()) {
            return (maxHeap.peek() + minHeap.peek()) / 2.0;
        }
        return maxHeap.peek();
    }
}

/**
 * Your MedianFinder object will be instantiated and called as such:
 * MedianFinder obj = new MedianFinder();
 * obj.addNum(num);
 * double param_2 = obj.findMedian();
 */


三刷

Follow up


Version #1 Two Heaps

76.63 %
class MedianFinder {

    /** initialize your data structure here. */
    PriorityQueue<Integer> maxHeap, minHeap;
    public MedianFinder() {
        // 2 heap
        // maxHeap, minHeap -> to keep maxHeap size == minHeap size or minHeap size + 1
        maxHeap = new PriorityQueue<>(Collections.reverseOrder());
        minHeap = new PriorityQueue<>();
    }
   
    public void addNum(int num) {
        if (maxHeap.isEmpty()) {
            maxHeap.offer(num);
            return;
        }
        if (num < maxHeap.peek()) {
            maxHeap.offer(num);
        } else {
            minHeap.offer(num);
        }
        adjust();
    }
   
    public double findMedian() {
        if (maxHeap.size() == minHeap.size()) {
            return (maxHeap.peek() + minHeap.peek()) / 2.0;
        }
        return maxHeap.peek();
    }
   
    private void adjust() {
        while (maxHeap.size() < minHeap.size()) {
            maxHeap.offer(minHeap.poll());
        }
        while (maxHeap.size() > minHeap.size() + 1) {
            minHeap.offer(maxHeap.poll());
        }
    }
}

二刷 LC

41.34 % 
class MedianFinder {

    // divide data into two parts ->   smaller half(size1) + larger half(size2)
    // always make sure that size1 == size2/ size2+1 -> if size1 == size2, median =  (maxOfSmallerHalf + minOfLargerHalf) / 2
    // else median = maxOfSmallerHalf
 
    /** initialize your data structure here. */
    PriorityQueue<Integer> smallerHalf;
    PriorityQueue<Integer> largerHalf;
    public MedianFinder() {
        smallerHalf = new PriorityQueue<>(10, Collections.reverseOrder());
        largerHalf = new PriorityQueue<>();
    }
 
    public void addNum(int num) {
        if (smallerHalf.isEmpty()) {
            smallerHalf.offer(num);
            return;
        }
     
        if (num <= smallerHalf.peek()) {
            smallerHalf.offer(num);
        } else {
            largerHalf.offer(num);
        }
         
        if (smallerHalf.size() < largerHalf.size()) {
            smallerHalf.offer(largerHalf.poll());
        } else if (smallerHalf.size() > largerHalf.size() + 1) {
            largerHalf.offer(smallerHalf.poll());
        }
    }
 
    public double findMedian() {
        if (smallerHalf.isEmpty()) {
            throw new RuntimeException("Empty number set");
        }
        if (smallerHalf.size() == largerHalf.size()) {
            return (smallerHalf.peek() + largerHalf.peek()) / 2.0;
        } else {
            return smallerHalf.peek();
        }
    }
}




一刷 LintCode
Using two heap
Time O(nlogn)
Space O(n)
public class Solution {
    /**
     * @param nums: A list of integers.
     * @return: the median of numbers
     */
    public int[] medianII(int[] nums) {
        // write your code here
        if (nums == null || nums.length == 0) return nums;
        int[] med = new int[nums.length];
        //max heap
        PriorityQueue<Integer> heap1 = new PriorityQueue<>(1, new Comparator<Integer>() {
            public int compare(Integer a, Integer b) {
                return b - a;
            }
        });
        //min heap
        PriorityQueue<Integer> heap2 = new PriorityQueue<>();
        int newNum;
        int currMed = nums[0];
        for (int i = 0; i < nums.length; i++) {
            newNum = nums[i];
            if (newNum <= currMed) heap1.offer(newNum);
            else heap2.offer(newNum);
            //heap2's size is at least 1 number
            if (heap1.size() < heap2.size()) {
                heap1.offer(heap2.poll());
            }
            if (heap1.size() > heap2.size() + 1) {
                heap2.offer(heap1.poll());
            }
            currMed = heap1.peek();
            med[i] = currMed;
        }
        return med;
    }
}

Thursday, April 6, 2017

28. Implement strStr() / strStr II

Version #2 Rabin Karp


O(m + n)
28.58 %
class Solution {
    public int BASE = 1000000;
    public int strStr(String haystack, String needle) {
        if (haystack == null || needle == null) return -1;
        if (needle.length() == 0) return 0;
     
        int target = 0;
        int power = 1; // weight of the highest bit
        int len = needle.length();
        for (int i = 0; i < len; i++) {
            target = (target * 31 + Character.getNumericValue(needle.charAt(i))) % BASE;
            power = power * 31 % BASE;
        }
        int hashCode = 0;
        for (int j = 0; j < haystack.length(); j++) {
            //       j = 3, len = 3
            // abc + d
            hashCode = (hashCode * 31 + Character.getNumericValue(haystack.charAt(j))) % BASE;
            // delete (j - len)
            if (j >= len) {
                hashCode = (hashCode - Character.getNumericValue(haystack.charAt(j - len)) * power) % BASE;
                if (hashCode < 0) hashCode += BASE;
            }
         
         
            if (hashCode == target) {
                // double check to ensure correctness
                //haystack index [j - len + 1, j]
                if (haystack.substring(j - len + 1, j + 1).equals(needle)) return j - len + 1;
            }
        }
        return -1;
    }
}


Version #1 KMP
看了普林斯顿老爷爷的讲解感觉理解的比较深刻了,但是自己写还是不熟练
LeetCode上面有一个人dfa只用了一维数组,没懂为何
https://discuss.leetcode.com/topic/3576/accepted-kmp-solution-in-java-for-reference

网上另一个讲解

暂时先这样吧以后有空再看看



public class Solution {
    /**
     * @param source a source string
     * @param target a target string
     * @return an integer as index
     */
    public int strStr2(String source, String target) {
        // Write your code here
        if (source == null || target == null || source.length() < target.length()) return -1;
        if (target.length() == 0) return 0;
        int i, j, N = source.length(), M = target.length();
        int[][] dfa = dfaBuilder(target);
        for (i = 0, j = 0; i < N && j < M; i++) {
            j = dfa[source.charAt(i) - 'a'][j];
        }
        if (j == M) return i - M;
        return -1;
    }
 
    public int[][] dfaBuilder(String target) {
        int M = target.length();
        int R = 26; //ASCII
        int[][] dfa = new int[R][M];
        dfa[target.charAt(0) - 'a'][0] = 1; //The 1st match state
        for (int x = 0, j = 1; j < M; j++) {
            for (int c = 0; c < R; c++) {
                dfa[c][j] = dfa[c][x]; //copy mismatch cases
                dfa[target.charAt(j) - 'a'][j] = j + 1; //set the match case
                x = dfa[target.charAt(j) - 'a'][x];
            }
        }
        return dfa;
    }
}

二刷
Version #1 Brute Force
Runtime: 0 ms, faster than 100.00% of Java online submissions for Implement strStr().
Memory Usage: 40.3 MB, less than 90.37% of Java online submissions for Implement strStr().

Time O(mn)
class Solution {
    public int strStr(String haystack, String needle) {
        if (haystack == null || needle == null || needle.equals("")) {
            return 0;
        }
        
        int needleLen = needle.length();
        int haystackLen = haystack.length();
        for (int start = 0; start + needleLen <= haystackLen; start++) {
            if (matches(haystack, start, needle)) {
                return start;
            }
        }
        return -1;
    }
    
    // abcde
    // qqqqabcde
    private boolean matches(String source, int start, String target) {
        for (int i = 0; i < target.length(); i++) {
            if (start + i >= source.length()) {
                return false;
            }
            if (source.charAt(start + i) != target.charAt(i)) {
                return false;
            }
        }
        return true;
    }
}
















Tuesday, March 21, 2017

94. Binary Tree Inorder Traversal

Version #3 Very Important
2ND TRY Stack Traversal
We have two operations -> push and pop
push of curr makes sure that all nodes are order by their in-order-traversal order
pop takes that into result list

Since we are doing these two things at the same time, we stop until curr == null && stack.isEmpty()

100.00 %
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
Deque<TreeNode> deque = new ArrayDeque<>();
TreeNode curr = root;
while (curr != null || !deque.isEmpty()) {
while (curr != null) {
deque.addFirst(curr);
curr = curr.left;
}
curr = deque.removeFirst();
result.add(curr.val);
curr = curr.right;
}
return result;
       
    }
}

1ST TRY
Traversal Method
https://www.kancloud.cn/kancloud/data-structure-and-algorithm-notes/73026
参考了这里面说的四步:
  1. 首先需要一直对左子树迭代并将非空节点入栈
  2. 节点指针为空后不再入栈
  3. 当前节点为空时进行出栈操作,并访问栈顶节点
  4. 将当前指针p用其右子节点替代
步骤2,3,4对应「左根右」的遍历结构,只是此时的步骤2取的左值为空。
我的理解:
用curr对整个Tree进行遍历
Step1
如果curr不是null,就一直向左找,同时curr入栈。当curr到达null时,它的parent为最左节点,也是最后一个进入stack的node

Step2
此时curr = stack.pop() 获得未访问过的最左节点,对该点进行operation

Step3
对于当前curr来说,可以保证它的左边和它自身都被遍历过了,于是开始搜索它的右边
curr = curr.right
若curr不为null, 则在step1的讨论范围之内
若curr为null,则直接进入step2


public class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<Integer>();
        if (root == null) return result;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode curr = root;
        while (curr != null || !stack.isEmpty()) {
            if (curr != null) {
                stack.add(curr);
                curr = curr.left;
                continue;
            }
            //curr is null
            curr = stack.pop();
            result.add(curr.val);
            curr = curr.right;
        }
        return result;
    }
}

Version #1 Recursion 每一次都new了新的list,效率比较低
44.48%
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<Integer>();
        if (root == null) return result;
        List<Integer> left = inorderTraversal(root.left);
        List<Integer> right = inorderTraversal(root.right);
        result.addAll(left);
        result.add(root.val);
        result.addAll(right);
        return result;
    }
}

Version #2 Recursion 把result list 作为一个参数传进了helper函数,以外的是时间并没有提高
44.48%
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<Integer>();
        inorderTraversalHelper(root, result);
        return result;
    }
    private void inorderTraversalHelper(TreeNode root, List<Integer> result) {
        if (root == null) return;
        inorderTraversalHelper(root.left, result);
        result.add(root.val);
        inorderTraversalHelper(root.right, result);
    }
}

Monday, March 20, 2017

226. Invert Binary Tree

三刷

100.00 %
class Solution {
    public TreeNode invertTree(TreeNode root) {
        if (root != null) {
            TreeNode left = root.left;
            root.left = invertTree(root.right);
            root.right = invertTree(left);
        }
        return root;
    }
}

二刷
完全一样
27.47 %
public class Solution {
    public TreeNode invertTree(TreeNode root) {
        if (root == null) return null;
        TreeNode left = invertTree(root.left);
        TreeNode right = invertTree(root.right);
        root.left = right;
        root.right = left;
        return root;
    }
}

一刷
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode invertTree(TreeNode root) {
        if (root == null) return root;
        TreeNode left = invertTree(root.left);
        TreeNode right = invertTree(root.right);
        root.left = right;
        root.right = left;
        return root;
    }
}

Saturday, March 11, 2017

70. Climbing Stairs

四刷 06/2022
Version #1 DP with Constant space
Time O(N)
Space O(1)
Runtime: 0 ms, faster than 100.00% of Java online submissions for Climbing Stairs.
Memory Usage: 40.9 MB, less than 41.40% of Java online submissions for Climbing Stairs.
class Solution {
    public int climbStairs(int n) {
        // standing at one stair i, the result is ways to reach stair i - 2 + ways to reach stair i - 1
        // count 1 = 1
        // coutn 2 = 2
        if (n <= 2) {
            return n;
        }
        int prevprev = 1;
        int prev = 2;
        for (int i = 3; i <= n; i++) {
            int curr = prev + prevprev;
            prevprev = prev;
            prev = curr;
        }
        return prev;
    }
}

三刷
100.00 % 
class Solution {
    public int climbStairs(int n) {
        if (n <= 1) {
            return 1;
        }
        int prevprev = 1; // 0
        int prev = 1; // 1
        for (int i = 2; i <= n; i++) {
            int curr = prevprev + prev;
            prevprev = prev;
            prev = curr;
        }
        return prev;
    }
}

一刷
public class Solution {
    public int climbStairs(int n) {
        if (n <= 1) {
            return n;
        }
        int lastlast = 1;
        int last = 1;
        int temp = 0;
        for (int i = 2; i <= n; i++) {
            temp = lastlast + last;
            lastlast = last;
            last = temp;
        }
        return temp;
     
    }
}

二刷
这次纯自己写的
不如一刷的标答简洁
用了额外O(n) 的space complexity
其实可以直接通过2个 variable rolling的方式实现

public class Solution {
    /**
     * @param n: An integer
     * @return: An integer
     */
    public int climbStairs(int n) {
        // write your code here
        if (n <= 1) return 1;
        int[] ways = new int[n + 1];
        ways[0] = 1;
        ways[1] = 1;
        for (int i = 2; i <= n; i++) {
            ways[i] = ways[i - 1] + ways[i - 2];
        }
        return ways[n];
    }
}

240. Search a 2D Matrix II

三刷 07/2022
Version #1 Iteration
第一个想法是binary search
后来发现是不对的,因为并不是整体有序的,row更小的行有可能包含比下面的row更大的数
Time O(M + N)
Space O(1)
Runtime: 9 ms, faster than 80.42% of Java online submissions for Search a 2D Matrix II.
Memory Usage: 57.6 MB, less than 60.49% of Java online submissions for Search a 2D Matrix II.
class Solution { public boolean searchMatrix(int[][] matrix, int target) { int y = matrix.length - 1; int x = 0; while (y >= 0 && x < matrix[0].length) { if (matrix[y][x] == target) { return true; } if (matrix[y][x] > target) { y--; } else { x++; } } return false; } }


二刷
if the target is greater than the value in current position, then the target can not be in entire row of current position because the row is sorted, if the target is less than the value in current position, then the target can not in the entire column because the column is sorted too. We can rule out one row or one column each time, so the time complexity is O(m+n).
17.19 %
class Solution { public boolean searchMatrix(int[][] matrix, int target) { if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) { return false; } // Search from left bottom int row = matrix.length - 1; int col = 0; while (row >= 0 && col < matrix[0].length) { if (matrix[row][col] == target) { return true; } else if (matrix[row][col] > target) { row--; } else { col++; } } return false; } }
一刷
public class Solution {
   public boolean searchMatrix(int[][] matrix, int target) {
       if (matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0) {
return false;
}
int rows = matrix.length;
int cols = matrix[0].length;
int x = rows - 1;
int y = 0;
while (x >= 0 && y < cols) {
if (matrix[x][y] == target) return true;
if (matrix[x][y] < target) {
y++;
} else {
x--;
}
}
return false;
   }
}