2015年11月5日星期四

Leetcode 277 Find the Celebrity

Suppose you are at a party with n people (labeled from 0 to n - 1) and among them, there may exist one celebrity. The definition of a celebrity is that all the other n - 1people know him/her but he/she does not know any of them.
Now you want to find out who the celebrity is or verify that there is not one. The only thing you are allowed to do is to ask questions like: "Hi, A. Do you know B?" to get information of whether A knows B. You need to find out the celebrity (or verify there is not one) by asking as few questions as possible (in the asymptotic sense).
You are given a helper function bool knows(a, b) which tells you whether A knows B. Implement a function int findCelebrity(n), your function should minimize the number of calls to knows.
Note: There will be exactly one celebrity if he/she is in the party. Return the celebrity's label if there is a celebrity in the party. If there is no celebrity, return -1.
Solution 1: At most only one celebrity. Use two pointer to search. If i know j, i is not celebrity; if i is not know j then j is not celebrity. When they meet, check the meeting element to be real celebrity or not.
 public class Solution extends Relation {  
   public int findCelebrity(int n) {  
     int i=0;  
     for (int j=1; j<n; j++) {  
       if (knows(i,j)) i=j;  
     }  
     for (int j=0; j<n; j++) {  
       if (i!=j && (knows(i,j) || !knows(j,i))) return -1;  
     }  
     return i;  
   }  
 }  

Leetcode 276 Paint Fence

There is a fence with n posts, each post can be painted with one of the k colors.
You have to paint all the posts such that no more than two adjacent fence posts have the same color.
Return the total number of ways you can paint the fence.
Note:
n and k are non-negative integers.
Solution 1: DP question. Maintain an array of same and diff. Transaction formula will be same[i]=diff[i-1]; diff[i]=(same[i-1]+diff[i-1])*(n-1). Optimize to O(1) space as below:
 public class Solution {  
   public int numWays(int n, int k) {  
     if (n==0) return 0;  
     int same=0, diff=k;  
     for (int i=1; i<n; i++) {  
       int pre=same;  
       same=diff;  
       diff=(pre+diff)*(k-1);  
     }  
     return same+diff;  
   }  
 }  

Leetcode 275 H-Index II

Follow up for H-Index: What if the citations array is sorted in ascending order? Could you optimize your algorithm?
Solution 1: use binary search, can be solved in O(logn).
 public class Solution {  
   public int hIndex(int[] citations) {  
     int n=citations.length;  
     int lo=0, hi=n;  
     while (lo<hi) {  
       int mid=lo+(hi-lo)/2;  
       if (citations[mid]>=n-mid) hi=mid;  
       else lo=mid+1;  
     }  
     return n-lo;  
   }  
 }  

Leetcode 274 H-Index

Given an array of citations (each citation is a non-negative integer) of a researcher, write a function to compute the researcher's h-index.
According to the definition of h-index on Wikipedia: "A scientist has index h if h of his/her N papers have at least h citations each, and the other N − h papers have no more than h citations each."
For example, given citations = [3, 0, 6, 1, 5], which means the researcher has 5 papers in total and each of them had received 3, 0, 6, 1, 5 citations respectively. Since the researcher has 3 papers with at least 3 citations each and the remaining two with no more than 3 citations each, his h-index is 3.
Note: If there are several possible values for h, the maximum one is taken as the h-index.
Solution 1: Use a count array, count[i] to store the number of papers has i citations. Then iterate the count array from end to start, calculate the sum which is the num of patter with more than i citations. if sum>=i, i is what we want to return.
 public class Solution {  
   public int hIndex(int[] citations) {  
     int n=citations.length;  
     int[] count=new int[n+1];  
     for (int num: citations) {  
       if (num>=n) count[n]++;  
       else count[num]++;  
     }  
     int total=0;  
     for (int i=n; i>0; i--) {  
       total+=count[i];  
       if (total>=i) return i;  
     }  
     return 0;  
   }  
 }  

Leetcode 273 Integer to English Words

Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 231 - 1.
For example,
123 -> "One Hundred Twenty Three"
12345 -> "Twelve Thousand Three Hundred Forty Five"
1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
Solution 1: coding skill.
 public class Solution {  
   public String numberToWords(int num) {  
     String[] ones={"Zero","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve","Thirteen","Fourteen","Fifteen","Sixteen","Seventeen","Eighteen","Nineteen"};  
     String[] tens={"","","Twenty","Thirty","Forty","Fifty","Sixty","Seventy","Eighty","Ninety"};  
     String[] thousands={"Thousand","Million","Billion"};  
     int[] nums={1000,1000000,1000000000};  
     if (num<20) return ones[num];  
     if (num<100) return tens[num/10]+((num%10==0)?"":" "+ones[num%10]);  
     if (num<1000) return ones[num/100]+" Hundred"+((num%100==0)?"":" "+numberToWords(num%100));  
     for (int i=0; i<3; i++) {  
       if (i==2 || num<nums[i+1]) {  
         return numberToWords(num/nums[i])+" "+thousands[i]+((num%nums[i]==0)?"":" "+numberToWords(num%nums[i]));  
       }  
     }  
     return "";  
   }  
 }  

Leetcode 272 Closest Binary Search Tree Value II

Given a non-empty binary search tree and a target value, find k values in the BST that are closest to the target.
Note:
  • Given target value is a floating point.
  • You may assume k is always valid, that is: k ≤ total nodes.
  • You are guaranteed to have only one unique set of k values in the BST that are closest to the target.
Follow up:
Assume that the BST is balanced, could you solve it in less than O(n) runtime (where n = total nodes)?
Solution 1: travel through the BST to build stack left stack and right stack. Each time find the min peek of the two, pop and rebuild one of the stack.
 public class Solution {  
   public List<Integer> closestKValues(TreeNode root, double target, int k) {  
     Deque<TreeNode> left=new LinkedList<>();  
     Deque<TreeNode> right=new LinkedList<>();  
     TreeNode x=root;  
     while (x!=null) {  
       if (x.val>target) {  
         right.push(x);  
         x=x.left;  
       }  
       else {  
         left.push(x);  
         x=x.right;  
       }  
     }  
     List<Integer> res=new ArrayList<>();  
     while (res.size()<k) {  
       if (left.isEmpty()) nextRight(right,res);  
       else if (right.isEmpty()) nextLeft(left,res);  
       else if (target-left.peek().val<right.peek().val-target) nextLeft(left,res);  
       else nextRight(right,res);  
     }  
     return res;  
   }  
   private void nextRight(Deque<TreeNode> right, List<Integer> res) {  
     TreeNode x=right.pop();  
     res.add(x.val);  
     x=x.right;  
     while (x!=null) {  
       right.push(x);  
       x=x.left;  
     }  
   }  
   private void nextLeft(Deque<TreeNode> left, List<Integer> res) {  
     TreeNode x=left.pop();  
     res.add(x.val);  
     x=x.left;  
     while (x!=null) {  
       left.push(x);  
       x=x.right;  
     }  
   }  
 }  

Leetcode 271 Encode and Decode Strings

Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings.
Machine 1 (sender) has the function:
string encode(vector<string> strs) {
  // ... your code
  return encoded_string;
}
Machine 2 (receiver) has the function:
vector<string> decode(string s) {
  //... your code
  return strs;
}
So Machine 1 does:
string encoded_string = encode(strs);
and Machine 2 does:
vector<string> strs2 = decode(encoded_string);
strs2 in Machine 2 should be the same as strs in Machine 1.
Implement the encode and decode methods.
Note:
  • The string may contain any possible characters out of 256 valid ascii characters. Your algorithm should be generalized enough to work on any possible characters.
  • Do not use class member/global/static variables to store states. Your encode and decode algorithms should be stateless.
  • Do not rely on any library method such as eval or serialize methods. You should implement your own encode/decode algorithm.
Solution 1: Use KMP, insert needles between the String to Serialize. 
 public class Codec {  
   String needle="#21kmpd#";  
   // Encodes a list of strings to a single string.  
   public String encode(List<String> strs) {  
     StringBuilder sb=new StringBuilder();  
     for (String s: strs) {  
       sb.append(s);  
       sb.append(needle);  
     }  
     return sb.toString();  
   }  
   // Decodes a single string to a list of strings.  
   public List<String> decode(String s) {  
     int n=s.length();  
     int m=needle.length();  
     int[] next=new int[m];  
     List<String> res=new ArrayList<>();  
     next[0]=-1;  
     int k=-1, j=0;  
     while (j<m-1) {  
       if (k==-1 || needle.charAt(j)==needle.charAt(k)) {  
         j++;  
         k++;  
         next[j]=needle.charAt(j)==needle.charAt(k)?next[k]:k;  
       }  
       else k=next[k];  
     }  
     int i=0;  
     while (i<n) {  
       int pre=i;   
       j=0;  
       while (j<m && i<n) {  
         if (j==-1 || s.charAt(i)==needle.charAt(j)) {  
           i++;  
           j++;  
         }  
         else j=next[j];  
       }  
       res.add(s.substring(pre,i-j));  
     }  
     return res;  
   }  
 }