Find Kth Largest Number


public class Solution {
        public int findKthLargest(int[] nums, int k) {
            return findK(nums,nums.length - k,0,nums.length-1);
        }

        private int findK(int[] nums,int k, int start, int end){
            int parti = nums[start],i=start,m=start;
            for(int j=start+1;j<=end;j++){
                if(nums[j]>parti)
                    continue;
                if(nums[j]<=parti){
                    swap(nums,++i,j);
                    if(nums[j] != parti)
                        swap(nums,m++,i);
                }
            }
            if(k>=m && k<=i)
                return nums[k];
            else if(k < m)
                return findK(nums,k,start,m-1);
            else 
                return findK(nums,k,i+1,end);
        }

        private void swap(int[] nums, int a, int b){
            int temp = nums[a];
            nums[a] = nums[b];
            nums[b] = temp;
        }
    }

Count Primes


public class Solution {
    public int countPrimes(int n) {
        int res = 0;
        boolean[] used = new boolean[n];
        for (int i = 2; i <= Math.sqrt(n); i++) {
             if (!used[i - 1]) {
                int temp = i * i;
                while (temp < n) {
                    used[temp - 1] = true;
                    temp += i;
                }
            }
        }
        for (int i = 2; i < n; i++) {
            if (!used[i - 1]) {
                res++;
            }
        }
        return res;
    }
}

Number of 1bits


public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int count = 0;
        while(n != 0){
            n = n & (n-1);
            count++;
        }
        return count;
    }
}

Largest Number


public class Solution {
    public String largestNumber(int[] num) {
        StringBuilder res = new StringBuilder();
        if (num == null || num.length == 0)
            return null;

        //conver Integer to string
        String[] nums = new String[num.length];
        for (int i = 0; i < num.length; i++)
            nums[i] = Integer.toString(num[i]);

        //Define comparator
        Comparator<String> comp = new Comparator<String>()
                {
                    @Override
                    public int compare(String o1, String o2)
                    {
                        return (o1+o2).compareTo(o2+o1);
                    }
                };
         Arrays.sort(nums, comp);

         //The new number should not start with 0 unless it is 0
        if (nums[nums.length-1].equals("0")) 
            return "0";

        for (int i = nums.length-1; i >= 0; i--)
         {
             res.append(nums[i]);
         }

        return res.toString();
    }
}

Major Element


public class Solution {
    public int majorityElement(int[] nums) {
        // moore's voting algorithm
        // find candidate element
        if (nums.length == 1) return nums[0];
        int majorityIndex = 0, count = 1;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] == nums[majorityIndex]) count++;
            else count--;
            if (count == 0) {
                majorityIndex = i;
                count = 1;
            }
        }
        // check if candidate is the majority element
        return nums[majorityIndex];
    }
}

Reverse Words in a String


public class Solution {
    public char[] reverse(char[] arr, int i, int j) {
        while (i < j) {
            char tmp = arr[i];
            arr[i++] = arr[j];
            arr[j--] = tmp;
        }
        return arr;
    }
    public String reverseWords(String s) {
        // reverse the whole string and convert to char array
        char[] str = reverse(s.toCharArray(), 0, s.length()-1);
        int start = 0, end = 0; // start and end positions of a current word
        for (int i = 0; i < str.length; i++) {
            if (str[i] != ' ') { // if the current char is letter 
                str[end++] = str[i]; // just move this letter to the next free pos
            } else if (i > 0 && str[i-1] != ' ') { // if the first space after word
                reverse(str, start, end-1); // reverse the word
                str[end++] = ' '; // and put the space after it
                start = end; // move start position further for the next word
            }
        }
        reverse(str, start, end-1); // reverse the tail word if it's there
        // here's an ugly return just because we need to return Java's String
        // also as there could be spaces at the end of original string 
        // we need to consider redundant space we have put there before
        return new String(str, 0, end > 0 && str[end-1] == ' ' ? end-1 : end);
    }
}

Sqrt(x)


public class Solution {
    public int mySqrt(int x) {
        if (x == 0)
            return 0;
        int left = 1, right = x;
        while (true) {
            int mid = left + (right - left)/2;
            if (mid > x/mid) {
                right = mid - 1;
            } else {
                if (mid + 1 > x/(mid + 1))
                    return mid;
                left = mid + 1;
            }
        }
    }
}

pow(x,n)


public class Solution {
    public double myPow(double x, int n) {
        if(n==0) return 1;
        if(x==0) return 0;
        int sign = (x<0)?-1 : 1;
        double tmpX = Math.abs(x);
        int tmpN = Math.abs(n);
        double pow1 = myPow(tmpX,tmpN/2);
        double pow2;
        if(tmpN%2 == 1){pow2 = pow1*tmpX;}
        else pow2 = pow1;
        double pow3;
        pow3 = (tmpN%2==1)?pow1*pow2*sign:pow1*pow2;
        return (n>0)?pow3:1/pow3;
    }
}

Divide Two Integers


public class Solution {
    public int divide(int dividend, int divisor) {
        //Reduce the problem to positive long integer to make it easier.
        //Use long to avoid integer overflow cases.
        int sign = 1;
        if ((dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0))
            sign = -1;
        long ldividend = Math.abs((long) dividend);
        long ldivisor = Math.abs((long) divisor);
        //Take care the edge cases.
        if (ldivisor == 0) return Integer.MAX_VALUE;
        if ((ldividend == 0) || (ldividend < ldivisor)) return 0;
        long lans = ldivide(ldividend, ldivisor);
        int ans;
        if (lans > Integer.MAX_VALUE){ //Handle overflow.
            ans = (sign == 1)? Integer.MAX_VALUE : Integer.MIN_VALUE;
        } else {
            ans = (int) (sign * lans);
        }
        return ans;
    }
    private long ldivide(long ldividend, long ldivisor) {
        // Recursion exit condition
        if (ldividend < ldivisor) return 0;
        //  Find the largest multiple so that (divisor * multiple <= dividend), 
        //  whereas we are moving with stride 1, 2, 4, 8, 16...2^n for performance reason.
        //  Think this as a binary search.
        long sum = ldivisor;
        long multiple = 1;
        while ((sum+sum) <= ldividend) {
            sum += sum;
            multiple += multiple;
        }
        //Look for additional value for the multiple from the reminder (dividend - sum) recursively.
        return multiple + ldivide(ldividend - sum, ldivisor);
    }
}

Plus One


public class Solution {
    public int[] plusOne(int[] digits) {

        int n = digits.length;
        for(int i=n-1; i>=0; i--) {
            if(digits[i] < 9) {
                digits[i]++;
                return digits;
            }

            digits[i] = 0;
        }

        int[] newNumber = new int [n+1];
        newNumber[0] = 1;

        return newNumber;
    }
}

Add Binary


public class Solution {
    public String addBinary(String a, String b) {
        int lena = a.length();
        int lenb = b.length();
        int i =0, carry = 0;
        String res = "";
        while(i<lena || i<lenb || carry!=0){
            int x = (i<lena) ? Character.getNumericValue(a.charAt(lena - 1 - i)) : 0;
            int y = (i<lenb) ? Character.getNumericValue(b.charAt(lenb - 1 - i)) : 0;
            res = (x + y + carry)%2 + res;
            carry = (x + y + carry)/2;
            i++;
        }
        return res;
    }
}
posted on 2016-06-28 16:56  岳阳楼  阅读(198)  评论(0)    收藏  举报