zoukankan      html  css  js  c++  java
  • First Missing Positive

    Given an unsorted integer array, find the first missing positive integer.

    For example,
    Given [1,2,0] return 3,
    and [3,4,-1,1] return 2.

    Your algorithm should run in O(n) time and uses constant space.

    Subscribe to see which companies asked this question

    Show Tags
    Show Similar Problems
     
    class Bitmap {
    public:
        Bitmap() {
            int i = 0;
            while (i < size) {
                bitmap[i] = 0;
                i++;
            }
        }
    
    /*
    
    * 设置第i位
    
    * i >> SHIFT 相当于 i / (2 ^ SHIFT),
    
    * i&MASK相当于mod操作 m mod n 运算
    
    */
    
        void bitset(int i) {
    
            bitmap[i >> SHIFT] |= 1 << (i & MASK);
    
        }
    
    //获取第i位
    
        int bittest(int i) {
    
            return bitmap[i >> SHIFT] & (1 << (i & MASK));
    
    
        }
    
    //清除第i位
    
        int bitclear(int i) {
    
            return bitmap[i >> SHIFT] & ~(1 << (i & MASK));
    
        }
    private:
    
        const static int INT_BITS  = sizeof(int);
    
        const static int SHIFT =  5; // 2^5=32
    
        const static int  MASK = 0x1f; // 2^5=32
    
        const static int  _MAX  = 1024;//max number
        const static int size = _MAX / INT_BITS;
        int bitmap[size];
    };
    
    class Solution {
    public:
        int firstMissingPositive(vector<int>& nums) {
            int size_num = nums.size();
            int i;
            int positive_num = 0;
            Bitmap bitmap;
            
            for (i=0; i<size_num; i++) {
                if (nums[i] > 0 && bitmap.bittest(nums[i]) == 0) {
                    positive_num++;
                    bitmap.bitset(nums[i]);
                }
            }
            
            for (i=1; i<=positive_num; i++) {
                if (bitmap.bittest(i) == 0) {
                    return i;
                }
            }
            return i;
        }
    };
  • 相关阅读:
    类属性、实例属性
    多态
    重载
    多继承
    继承介绍以及单继承
    析构
    构造
    self
    方法
    属性
  • 原文地址:https://www.cnblogs.com/SpeakSoftlyLove/p/5184716.html
Copyright © 2011-2022 走看看