题目详情

Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.

就是给一个数组,如果数组内有重复元素就返回true,否则返回false。

Example:

Input: matrix = [0, 1, 0, 3, 12]

Output: true

思路

  • 太简单了,跟数组去重一样

具体代码

  1. /**
  2. * @param {number[]} nums
  3. * @return {boolean}
  4. */
  5. var containsDuplicate = function(nums) {
  6. let obj = {}
  7. for(let i = 0, len = nums.length; i < len; i++) {
  8. if(obj[nums[i]]){
  9. return true
  10. } else {
  11. obj[nums[i]] = 1
  12. }
  13. }
  14. return false
  15. };

Array - 661. Image Smootheroes

题目详情

Given a 2D integer matrix M representing the gray scale of an image, you need to design a smoother to make the gray scale of each cell becomes the average gray scale (rounding down) of all the 8 surrounding cells and itself. If a cell has less than 8 surrounding cells, then use as many as you can.

题目给了我们一个2d M array,让我们平滑处理图片。对于每一个cell,把它更新为 以自身为中心 3x3 的平均值。

就用常规方法做,新设一个 长度跟传入数组一样大小的arr,遍历M,对于每一个cell, 遍历以它为中心的3x3的cells,得到平均值,存入arr。

需要注意的就是,3x3的边界问题。

Example:

Input:
[[1,1,1],
[1,0,1],
[1,1,1]]

Output:
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]

Explanation:

For the point (0,0), (0,2), (2,0), (2,2): floor(3/4) = floor(0.75) = 0
For the point (0,1), (1,0), (1,2), (2,1): floor(5/6) = floor(0.83333333) = 0
For the point (1,1): floor(8/9) = floor(0.88888889) = 0

思路

  • 每个cell遍历周围方块

具体代码

/**
 * @param {number[][]} M
 * @return {number[][]}
 */
var imageSmoother = function(M) {
    let arr = Array.from(Array(M.length)).map(() => Array(M[0].length).fill(0))
    let val = 0
    let count = 0

    for(let i = 0, y = M.length; i < y; i++) {
        for(let j = 0, x = M[0].length; j < x; j++) {

            for(let a = -1; a < 2; a++) {
                for(let b = -1; b < 2; b++) {
                    if(j + b >= 0 && i + a >= 0 && i + a < M.length && j + b <  M[0].length ) {
                        val += M[i + a][j + b];
                        count++
                    }
                }
            }
            arr[i][j] = Math.floor(val/count)
            val = 0
            count = 0
        }
    }
    return arr
};