题目详情

Given an array nums, write a function to move all 0’s to the end of it while maintaining the relative order of the non-zero elements.

For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].

大概意思就是,给你一个数组nums,操作数组变为 ‘0’ > 都在数组最后。

Example:

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

Output: [1, 3, 12, 0, 0]

Explanation: [0,1,0,3,12] —> [1,3,12,…] —> [1,3,12,0,0,0]

思路

  • 把非0项从后往前放,用个常量记录非0个数,遍历完在list后补0

具体代码

  1. var moveZeroes = function(nums) {
  2. let pos = 0;
  3. for(let i = 0; i < nums.length ; i++) {
  4. if(nums[i] !== 0) {
  5. nums[pos] = nums[i]
  6. pos++
  7. }
  8. }
  9. for(; pos < nums.length; pos++) {
  10. nums[pos] = 0
  11. }
  12. };

leetcode 268. Missing Number

题目详情

Given an array containing n distinct numbers taken from 0, 1, 2, …, n, find the one that is missing from the array.

他会给一个缺一个数的等差数列为1的顺序数组,求缺少的元素

Example 1:

Input: [1,0,3]

Output: 2

思路

  • 最直观的一个方法是用等差数列的求和公式求出0到n之间所有的数字之和
  • 然后再遍历数组算出给定数字的累积和
  • 然后做减法,差值就是丢失的那个数字

具体代码

var missingNumber = function(nums) {
    let len = nums.length
    let sum = 0
    for(let i = 0; i < len; i++) {
        sum += nums[i]
    }
    return 0.5 * len * (len + 1) - sum
};

leetcode 766. Toeplitz Matrix

题目详情

A matrix is Toeplitz if every diagonal from top-left to >bottom-right has the same element.

Now given an M x N matrix, return True if and only if the matrix is Toeplitz.

如果一个矩阵的每一条斜对角线(左上到右下)上的元素都相等,则我们称它为托普利兹矩阵。现在输入一个M*N大小的矩阵,如果它是一个托普利兹矩阵,则返回true,如果不是,返回false。

Example 1:

Input: matrix = [

[3,2,1,5],

[7,3,2,1],

[4,7,3,2]

]

Output: True

思路

  • 遍历每一个元素,比较这个元素和它右下角元素的值是否相等,如果不相等,直接返回false,停止遍历。

具体代码

var isToeplitzMatrix = function(arr) {
    var m = arr[0].length -1;
    var n = arr.length-1;
    for(var i = 0; i < n; i++) {
        for(var j = 0; j <m; j++) {
            if(arr[i][j] != arr[i+1][j+1]) {
                return false
            }
        }
    }
    return true
};

2018.4.17 — End