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
  • 相关阅读:
    ios7.0结合storyborad实现页面跳转的总结
    ios上取得设备唯一标志的解决方案
    【iOS】Objective-C简约而不简单的单例模式
    ios应用启动后的自动版本检测方式
    linux安装常用软件和查询基本信息
    配置本地yum仓库
    RedHat 6.5 上将系统语言修改为中文
    RedHat7.4配置yum网络源
    linux环境中,两个不同网段的机器互通
    redhat 配置eth0网卡
  • 原文地址:https://www.cnblogs.com/theskulls/p/4889790.html
Copyright © 2011-2022 走看看