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)
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"))
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()
}
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)
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)
}
}