leetcode刷题记录---19.11.15 map,常数时间插入删除和获取随机元素(微软面试题,用两种方法解决,unordered_set和map+vector)

1.存在重复元素

题目描述:

给定一个整数数组,判断是否存在重复元素。

如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。

示例 1:

输入: [1,2,3,1]
输出: true
示例 2:

输入: [1,2,3,4]
输出: false
示例 3:

输入: [1,1,1,3,3,4,3,2,4,2]
输出: true

class Solution {
public:
    bool containsDuplicate(vector<int>& nums) {
        map<int,int> zyw;
        for(auto ch:nums){
            if(zyw[ch]==1) return true;
            else
                zyw[ch]++;
        }
        return false;        
    }
};

2.常数时间插入,删除和获取随机元素

题目描述:

设计一个支持在平均 时间复杂度 O(1) 下,执行以下操作的数据结构。

insert(val):当元素 val 不存在时,向集合中插入该项。
remove(val):元素 val 存在时,从集合中移除该项。
getRandom:随机返回现有集合中的一项。每个元素应该有相同的概率被返回。
示例 :

// 初始化一个空的集合。
RandomizedSet randomSet = new RandomizedSet();

// 向集合中插入 1 。返回 true 表示 1 被成功地插入。
randomSet.insert(1);

// 返回 false ,表示集合中不存在 2 。
randomSet.remove(2);

// 向集合中插入 2 。返回 true 。集合现在包含 [1,2] 。
randomSet.insert(2);

// getRandom 应随机返回 1 或 2 。
randomSet.getRandom();

// 从集合中移除 1 ,返回 true 。集合现在包含 [2] 。
randomSet.remove(1);

// 2 已在集合中,所以返回 false 。
randomSet.insert(2);

// 由于 2 是集合中唯一的数字,getRandom 总是返回 2 。
randomSet.getRandom();


思路(知识点):

无序set,unordered_set<int> uset;其实unorder暗示,它所包含的头文件的累的底层实现是---hash,因此,你可以在声明模板类的时候,传入自定义的哈希函数,准确的说是哈希函数子

1.可以把unordered_set看成一个集合,不允许插入相同的元素

2.对于unordered_set,它的insert/find/erase时间复杂度都是O(1)(unordered_map也是一样),最坏的复杂度是O(N)

3.出现O(N)时间复杂度的两种情况:

                   1.你的hash函数太烂了,导致很多不同元素的hash值都相同,全是碰撞,此时O(N)。这种情况较少见,因为基本数据类型,都有默认的hash函数,并且足够好,不会退化到O(N)

                   2.如果insert很多数据,会触发rehash,即hash表重建。。类似于向vector中不断添加元素,vector会resize。这种情况也不会频繁发生。

void advance(iterator& pos,int n)函数:可令迭代器前进n个元素。n可为负数。

.advance()并不检查迭代器是否超过序列的end(),所有对序列尾端调用operator++是一种未定义的操作行为。

本题的两种解法:1.unordered_set        2.vector+map

//unordered_set
class RandomizedSet {
	unordered_set<int> zyw;
public:
	RandomizedSet() {}
	bool insert(int val) {
		if (zyw.count(val) > 0) return false;
		zyw.insert(val);
		return true;
	}
	bool remove(int val) {
		if (zyw.count(val) > 0) {
			zyw.erase(val);
			return true;
		}
		return false;
	}
	int getRandom() {
		int size = zyw.size();
		int t = rand() % size;
		auto it = zyw.begin();
		advance(it, t);
		return *it;
	}
};




//map+vector
class RandomizedSet {
public:
    /** Initialize your data structure here. */
    unordered_map<int,int> zyw;
    vector<int> nums;
    RandomizedSet() {
       
    }
    
    /** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
    bool insert(int val) {
        if(zyw.count(val)>0) return false;
        else{
            nums.push_back(val);
            zyw[val] = nums.size()-1;
        }
        return true;
    }
    
    /** Removes a value from the set. Returns true if the set contained the specified element. */
    bool remove(int val) {
        if(zyw.count(val) == 0) return false;
        else{
            int last = nums.back();
            nums[zyw[val]] = last;
            zyw[last] = zyw[val];
            nums.pop_back();
            zyw.erase(val);
        }
        return true;
    }
    
    /** Get a random element from the set. */
    int getRandom() {
        return nums[rand()%zyw.size()];
    }
};

/**
 * Your RandomizedSet object will be instantiated and called as such:
 * RandomizedSet* obj = new RandomizedSet();
 * bool param_1 = obj->insert(val);
 * bool param_2 = obj->remove(val);
 * int param_3 = obj->getRandom();
 */

3.字符串中的第一个唯一字符

题目描述:

给定一个字符串,找到它的第一个不重复的字符,并返回它的索引。如果不存在,则返回 -1。

案例:

s = "leetcode"
返回 0.

s = "loveleetcode",
返回 2.

class Solution {
public:
    int firstUniqChar(string s) {
        map<char,int> zyw;
        for(auto &ch:s){
            zyw[ch]++;
        }
        for(int i = 0;i<s.size();++i){
            if(zyw[s[i]]==1) return i;
        }
        return -1;
    }
};

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值