zoukankan      html  css  js  c++  java
  • lintcode:落单的数

    题目:

    落单的数

    给出2*n + 1 个的数字,除其中一个数字之外其他每个数字均出现两次,找到这个数字。

    样例

    给出 [1,2,2,1,3,4,3],返回 4

    挑战

    一次遍历,常数级的额外空间复杂度

    解题:

    进去里面程序已经写好了,,也不知道是bug还是之前我网上复制程序的,但是竟然有记录,查看之前做的题目点进去也没有程序的,那一定是官方给的答案了。。。

    利用异或^运算,两个相同的数的异或的结果是0,就这样遍历之后的结果就是那个数了。这个题目准确率到目前16:31:24  2015-10-18  57%太高了,看了官方给的答案可能性已经很大了。

    Java程序:

    public class Solution {
        /**
         *@param A : an integer array
         *return : a integer 
         */
        public int singleNumber(int[] A) {
            if (A.length == 0) {
                return 0;
            }
    
            int n = A[0];
            for(int i = 1; i < A.length; i++) {
                n = n ^ A[i];
            }
    
            return n;
        }
    }
    View Code

    总耗时: 985 ms

    下面通过HashMap来实现,最坏情况下空间复杂度是O(n+1) 

    Java程序:

    public class Solution {
        /**
         *@param A : an integer array
         *return : a integer 
         */
        public int singleNumber(int[] A) {
            if (A.length == 0) {
                return 0;
            }
            HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
            for( int i = 0;i< A.length ; i++){
                if(map.containsKey(A[i])){
                    map.remove(A[i]);
                }else{
                    map.put(A[i],1);
                }
            }
            Object array[] = map.keySet().toArray() ;
            
            return (Integer)array[0];
        }
    }
    View Code

    总耗时: 1314 ms   1314...

    Python程序:

    class Solution:
        """
        @param A : an integer array
        @return : a integer
        """
        def singleNumber(self, A):
            # write your code here
            if A.length ==0:
                return 0 
            n = A[0]
            for i in range(1,len(A)):
                n = n ^ A[i]
            return n 
    View Code
  • 相关阅读:
    WPF Video Tutorials
    英语词汇看病
    回车键的含义
    勘误《新概念》IV
    2010年春季C语言程序设计答疑时间地点安排
    勘误《新概念》III
    A potentially dangerous Request.Form value was detected from the client
    推荐WPF的好书(图书)
    *英语词汇交通
    英语词汇房地产
  • 原文地址:https://www.cnblogs.com/theskulls/p/4889790.html
Copyright © 2011-2022 走看看