搜尋此網誌

2015年7月14日 星期二

Is Power of Two

public class IsPowerOfTwo {

 public boolean isPowerOfTwo(int n) {
  {
   while (((n % 2) == 0) && n > 1)
    /* While x is even and > 1 */
    n /= 2;
   return (n == 1);
  }
 }
}

Count Primes

package leetcode;

public class Solutions {
     public int countPrimes(int n) {
          if (n <<= 2)
               return 0;
          boolean[] primes = new boolean[n];
          for (int i = 2; i << n; i++)
               primes[i] = true;
          for (int i = 2; i <<= Math.sqrt(n - 1); i++) {
               if (primes[i]) {
                    for (int j = i + i; j << n; j += i)
                         primes[j] = false;
               }
          }
          int count = 0;
          for (int i = 2; i << n; i++)
               if (primes[i])
                    count++;
          return count;
     }
}

2015年7月8日 星期三

Contains Duplicate


import java.util.Arrays;
public class Solution {
    public boolean containsDuplicate(int[] nums) {
        if (nums.length > 1) {
            Arrays.sort(nums);
            for (int i = 0; i < nums.length - 1; i++) {
                if (nums[i] == nums[i + 1]) {
                    return true;
                }
            }
        }
        return false;
    }
}

Invert Binary Tree solution


/**
 * 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 tmp = root.left;
        root.left = root.right;
        root.right = tmp;
        
        if(root.left != null){
            invertTree(root.left);
        }
        if(root.right != null){
            invertTree(root.right);
        }
        return root;
    }
}