leetcode: 复杂度

1. single-number

Given an array of integers, every element appears twice except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

 给定一个数组,每个元素都出现2次除了其中的一个,找出只出现一次的数字注意:算法必须是线性时间复杂度,可以不使用额外空间实现吗? 

 

//异或运算,不同为1 相同为0
public
int singleNumber(int[] A) { int x = 0; for (int a : A) { x = x ^ a; } return x; }

 

 

2.single-number-ii

Given an array of integers, every element appears three times except for one. Find that single one.

Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

除了一个元素外,其它元素都是出现三次,求那个元素?

如果是除了一个元素,其它的都出现两次,则所有的数异或就是结果。

 

  int 数据共有32位,可以用32变量存储 这 N 个元素中各个二进制位上  1  出现的次数,最后 在进行 模三 操作,如果为1,那说明这一位是要找元素二进制表示中为 1 的那一位。

public class Solution{
    public int singleNumber(int [] A){
        if(A==null || A.length ==0){
            return -1;
        }
        int result=0;
        int[] bits=new int[32];
        for(int i=0;i<32;i++){
            for(int j=0;j<A.length;j++){
                bits[i]+=A[j]>>i&1;
                bits[i]%=3;
            }
            result |=(bits[i] << i);
        }
        return result;
    }
}
View Code

 

 

3.reverse-integer

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

public int reverse(int x) {
    int rev = 0;
    while(x != 0){
        rev = rev*10 + x%10;
        x = x/10;
    }
 
    return rev;
}
View Code

 

 
public int reverse(int x) {
    //flag marks if x is negative
    boolean flag = false;
    if (x < 0) {
        x = 0 - x;
        flag = true;
    }
 
    int res = 0;
    int p = x;
 
    while (p > 0) {
        int mod = p % 10;
        p = p / 10;
        res = res * 10 + mod;
    }
 
    if (flag) {
        res = 0 - res;
    }
 
    return res;
}
View Code

 

 

4.longest-common-prefix

Write a function to find the longest common prefix string amongst an array of strings.

找出所有字符串的最长公共前缀

public class Solution {
    
    // 1. Method 1, start from the first one, compare prefix with next string, until end;
    // 2. Method 2, start from the first char, compare it with all string, and then the second char
    // I am using method 1 here
    public String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }
        String prefix = strs[0];
        for(int i = 1; i < strs.length; i++) {
            int j = 0;
            while( j < strs[i].length() && j < prefix.length() && strs[i].charAt(j) == prefix.charAt(j)) {
                j++;
            }
            if( j == 0) {
                return "";
    }
            prefix = prefix.substring(0, j);
        }
        return prefix;
    }

}
View Code

 

posted @ 2016-03-30 09:50  zxqstrong  阅读(246)  评论(0编辑  收藏  举报