Posts

Showing posts from February, 2020

What is new in Java 8

1.  There are default methods and static methods in interfaces in Java 8. 2. Lamdas   Collections . sort ( list , ( o1 , o2 ) -> o1 . getTime () - o2 . getTime ()); Pre-Java8 Collections . sort ( list , new Comparator < Message >() { @Override public int compare ( Message o1 , Message o2 ) { return o1 . getTime () - o2 . getTime (); } });

Quicksort Java implementation

import java.util.Arrays; public class QuickSort { int [] data ; public void quicksort( int [] nums) { if (nums == null || nums. length == 0 ) return ; data = nums; sort( 0 , nums. length - 1 ); } private void sort( int left, int right) { if (right <= left) return ; int pivot = partition(left, right); sort(left, pivot - 1 ); sort(pivot + 1 , right); } /** * put all the numbers that are smaller than pivot to the left * **/ int partition( int left, int right) { int pivot = data [right]; int startIndex = left; for ( int i = left; i < right; i++) { //all the nums on the left of startIndex are smaller than pivot //the number at startIndex is >= pivot if ( data [i] < pivot) { swap(startIndex++, i); } } // put the pivot to the right position swap(startIndex, right); r...

Leetcode 158 Java solution with explanation

/**  * The read4 API is defined in the parent class Reader4.  *     int read4(char[] buf);  */ public class Solution extends Reader4 {     /**      * @param buf Destination buffer      * @param n   Number of characters to read      * @return    The number of actual characters read      */     // we need to save unused characters in a queue     // e.g. if we read 4 characters when calling read4, but we only need 2     // we save the 2 remaining characters in remain, we can use the remaining 2 chars first     // when next time the read(buf, n) is called     Queue<Character> remain = new LinkedList<>();       public int read(char[] buf, int n) {         int i = 0;         // check the remain queue first         while ...

Leetcode 953. Verifying an Alien Dictionary Java solution

class Solution {     public boolean isAlienSorted(String[] words, String order) {         int n = words.length;         Map<Character, Integer> orderMap = new HashMap<>();         for (int i = 0; i < order.length(); i++) {             orderMap.put(order.charAt(i),i);         }         for (int i = 0; i < n - 1; i++) {             if (!isSorted(words[i], words[i + 1], orderMap)) {                 return false;             }         }         return true;     }     boolean isSorted(String first, String two, Map<Character, Integer> map) {         int len1 = first.length();         int len2 = two.length();   ...