Algorithm

  1. Move all the 0s in the array to the end.
function moveZeros(arr) {
    let zeros = 0
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] === 0) {
            zeros += 1
        } else {
            arr[i - zeros] = arr[i]
        }
    }

    for (let i = arr.length - zeros; i < arr.length; i++) {
        arr[i] = 0
    }
}

let arr = [1, 3, 4, 0, 8, 9, 0, 7, 20, 3, 0, 6, 11]
moveZeros(arr)
console.log(arr)
  1. Given two strings s and t , write a function to determine if t is an anagram of s.
function lowerDictionary() {
    let obj = {}

    for (let i = 97; i < 123; i++) {
        obj[String.fromCharCode(i)] = 0
    }

    return obj
}

function isAnagram(s1, s2) {
    let d1 = lowerDictionary()
    let d2 = lowerDictionary()

    for (let item of s1) {
        d1[item] += 1
    }
    for (let item of s2) {
        d2[item] += 1
    }

    return JSON.stringify(d1) === JSON.stringify(d2)
}

console.log(isAnagram("ten", "net"))
  1. Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
    You may assume that the array is non-empty and the majority element always exist in the array.
function majorityElement(nums) {
    let stack = []

    nums.forEach(element => {
        if (stack.length === 0) {
            stack.push(element)
        } else {
            if (element === stack[stack.length - 1]) {
                stack.push(element)
            } else {
                stack.pop()
            }
        }
    })

    return stack.pop()
}
  1. A frog can jump one or two steps at a time. How many jumping methods are there when the frog jumps up an n-step? (Different order corresponds to different results)
function jumpFloor(number) {
    if (number <= 0) {
        return 0
    } else if (number === 1) {
        return 1
    } else if (number === 2) {
        return 2
    } else {
        return jumpFloor(number - 1) + jumpFloor(number - 2)
    }
}
  1. A frog can jump up a step or two at a time... It can also jump to level n at a time. Find out how many jumping methods the frog can use to jump up an n-step.
function jumpFloorII(number) {
    if (number <= 0) {
        return 0
    } else if (number === 1) {
        return 1
    } else {
        return 2 * jumpFloorII(number - 1)
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,430评论 0 10
  • 手杖式 1.坐在垫子中间,把臀肌向两侧拨开,脚后跟蹬,跟腱展开,脚趾指向上方,脚外侧向里收 2.呼气,小腿内收 3...
    小影米阅读 641评论 0 0
  • 谁也不是永动机,谁都有情绪高涨和低落的时候。所以就需要我们在状态不好的时候,及时调整自己的状态和情绪。大家状态不好...
    小李非刀阅读 1,134评论 4 5
  • 细数一下从去年7月份入市到现在丢失的机会:在刚进入币圈时6元左右买入一万个NEO,8块左右出掉;经历大跌的9.4时...
    花花呓语阅读 218评论 0 1