哈希

1.设计哈希映射

不使用任何内建的哈希表库设计一个哈希映射

具体地说,你的设计应该包含以下的功能

put(key, value):向哈希映射中插入(键,值)的数值对。如果键对应的值已经存在,更新这个值。
get(key):返回给定的键所对应的值,如果映射中不包含这个键,返回-1。
remove(key):如果映射中存在这个键,删除这个数值对。


示例:

MyHashMap hashMap = new MyHashMap();
hashMap.put(1, 1);
hashMap.put(2, 2);
hashMap.get(1); // 返回 1
hashMap.get(3); // 返回 -1 (未找到)
hashMap.put(2, 1); // 更新已有的值
hashMap.get(2); // 返回 1
hashMap.remove(2); // 删除键为2的数据
hashMap.get(2); // 返回 -1 (未找到)

class MyHashMap:
    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.key=[]
        self.value=[]


    def put(self, key: int, value: int) -> None:
        """
        value will always be non-negative.
        """
        if key in self.key:
            index=self.key.index(key)
            self.value[index]=value
        self.key.append(key)
        self.value.append(value)


    def get(self, key: int) -> int:
        """
        Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key
        """
        if key in self.key:
            index=self.key.index(key)
            return self.value[index]
        return -1

    def remove(self, key: int) -> None:
        """
        Removes the mapping of the specified value key if this map contains a mapping for the key
        """
        if key in self.key:
            index=self.key.index(key)
            self.key.pop(index)
            self.value.pop(index)

 2.有多少小于当前的数字

给你一个数组 nums,对于其中每个元素 nums[i],请你统计数组中比它小的所有数字的数目。

换而言之,对于每个 nums[i] 你必须计算出有效的 j 的数量,其中 j 满足 j != i 且 nums[j] < nums[i] 。

以数组形式返回答案。

示例 1:

输入:nums = [8,1,2,2,3]
输出:[4,0,1,1,3]
解释:
对于 nums[0]=8 存在四个比它小的数字:(1,2,2 和 3)。
对于 nums[1]=1 不存在比它小的数字。
对于 nums[2]=2 存在一个比它小的数字:(1)。
对于 nums[3]=2 存在一个比它小的数字:(1)。
对于 nums[4]=3 存在三个比它小的数字:(1,2 和 2)。

示例 2:

输入:nums = [6,5,4,8]
输出:[2,1,0,3]

示例 3:

输入:nums = [7,7,7,7]
输出:[0,0,0,0]

def smallerNumbersThanCurrent(nums) :
    n=len(nums)
    dict={}
    for num in nums:
        count=0
        i=0
        while i<n:
            if nums[i]<num:
                count+=1
            i+=1
        dict[num]=count
    return dict



nums = [6,5,4,8]
print(smallerNumbersThanCurrent(nums))

 

posted on 2020-10-21 16:46  happygril3  阅读(74)  评论(0)    收藏  举报

导航