刷题3 剑指 Offer — 哈希表

2020-08-09  本文已影响0人  可爱多小姐

Map对象的方法:

遍历方法:

Set实例对象的方法

遍历方法:

剑指 Offer 03. 数组中重复的数字

https://leetcode-cn.com/leetbook/read/illustrate-lcof/xzktv1/

在一个长度为 n 的数组 nums 里的所有数字都在 0~n-1 的范围内。数组中某些数字是重复的,但不知道有几个数字重复了,也不知道每个数字重复了几次。请找出数组中任意一个重复的数字。

var findRepeatNumber = function(nums) {
    var numsSet = new Set();
    for(var num of nums){
        if(numsSet.has(num)){
            return num;
        }else{
            numsSet.add(num)
        }
    }
    return false
};
var findRepeatNumber = function(nums) {
    for(var i = 0; i<nums.length ; i++){
        while(nums[i] != i){
            if(nums[i] == nums[nums[i]]){
                return nums[i]
            } 
            var tmp = nums[i];
            nums[i] =nums[tmp];
            nums[tmp] = tmp;
        }
    }
    return false
};

剑指 Offer 50. 第一个只出现一次的字符

https://leetcode-cn.com/leetbook/read/illustrate-lcof/xzzd25/

在字符串 s 中找出第一个只出现一次的字符。如果没有,返回一个单空格。 s 只包含小写字母。
示例: s = "abaccdeff" ,返回 "b";
示例: s = "" , 返回 " "

var firstUniqChar = function(s) {
    var maps = new Map();
    for(var num of s){
        maps.set(num, maps.has(num))
    }
     for(var num of s){
         if(maps.get(num)==0){
             return num;
         }
     }
    return " "
};
上一篇 下一篇

猜你喜欢

热点阅读