2021/10/25
1.在柠檬水摊上,每一杯柠檬水的售价为 5 美元。顾客排队购买你的产品,(按账单 bills 支付的顺序)一次购买一杯。
每位顾客只买一杯柠檬水,然后向你付 5 美元、10 美元或 20 美元。你必须给每个顾客正确找零,也就是说净交易是每位顾客向你支付 5 美元。
注意,一开始你手头没有任何零钱。
给你一个整数数组 bills ,其中 bills[i] 是第 i 位顾客付的账。如果你能给每位顾客正确找零,返回 true ,否则返回 false 。
var lemonadeChange = function(bills) {
let [count5, count10, count20] = [0, 0, 0]
for(let i = 0; i < bills.length; i++) {
if( bills[i] === 5 ) {
count5++
} else if( bills[i] === 10 ) {
if( count5 > 0) {
count5--
count10++
} else {
return false
}
} else if( bills[i] === 20 ) {
if ( count10 > 0 && count5 > 0 ) {
count20++
count10--
count5--
} else if( count5 > 3 ) {
count5 -=3
count20++
} else {
return false
}
}
}
return true
};
2.拥有最多糖果的孩子
给你一个数组 candies 和一个整数 extraCandies ,其中 candies[i] 代表第 i 个孩子拥有的糖果数目。
对每一个孩子,检查是否存在一种方案,将额外的 extraCandies 个糖果分配给孩子们之后,此孩子有 最多 的糖果。注意,允许有多个孩子同时拥有 最多 的糖果数目。
var kidsWithCandies = function(candies, extraCandies) {
let maxValue = Math.max(...candies)
let newArr = []
for(let i = 0; i< candies.length; i++) {
if( candies[i] + extraCandies >= maxValue) {
newArr.push(true)
} else {
newArr.push(false)
}
}
return newArr
};
3.比赛中的配对次数
给你一个整数 n ,表示比赛中的队伍数。比赛遵循一种独特的赛制:
如果当前队伍数是 偶数 ,那么每支队伍都会与另一支队伍配对。总共进行 n / 2 场比赛,且产生 n / 2 支队伍进入下一轮。
如果当前队伍数为 奇数 ,那么将会随机轮空并晋级一支队伍,其余的队伍配对。总共进行 (n - 1) / 2 场比赛,且产生 (n - 1) / 2 + 1 支队伍进入下一轮。
返回在比赛中进行的配对次数,直到决出获胜队伍为止。
var numberOfMatches = function(n) {
if( n == 1 ) return 0
let num = 0
while ( n != 1) {
if( n%2 == 0 ) {
n /= 2
num += n
} else {
n = ( n - 1 )/2
num += n
n += 1
}
}
return num
};
4.922. 按奇偶排序数组 II
给定一个非负整数数组 A, A 中一半整数是奇数,一半整数是偶数。
对数组进行排序,以便当 A[i] 为奇数时,i 也是奇数;当 A[i] 为偶数时, i 也是偶数。
你可以返回任何满足上述条件的数组作为答案。
var sortArrayByParityII = function(nums) {
let [ odd, even, newArr ] = [ 1, 0, [] ]
for(let i = 0; i < nums.length; i++) {
if( nums[i]2 == 0 ) {
newArr[even] = nums[i]
even += 2
} else {
newArr[odd] = nums[i]
odd += 2
}
}
return newArr
};
5.有序数组中出现次数超过25%的元素
给你一个非递减的 有序 整数数组,已知这个数组中恰好有一个整数,它的出现次数超过数组元素总数的 25%。
请你找到并返回这个整数
var findSpecialInteger = function(arr) {
let total = arr.length
let newArr = []
newArr.length = Math.max(...arr) + 1
for(let i = 0; i < newArr.length; i++) {
newArr[i] = 0
}
for(let i = 0; i < arr.length; i++) {
newArr[arr[i]]++
}
if(Math.max(...newArr)/total > 0.25 ) return newArr.indexOf(Math.max(...newArr))
return -1
};
6.按摩师
一个有名的按摩师会收到源源不断的预约请求,每个预约都可以选择接或不接。在每次预约服务之间要有休息时间,因此她不能接受相邻的预约。给定一个预约请求序列,替按摩师找到最优的预约集合(总预约时间最长),返回总的分钟数。
var massage = function(nums) {
let a = 0, b = 0;
for (let i = 0; i < nums.length; i++) {
let c = Math.max(b, a + nums[i]);
a = b;
b = c;
}
return b;
};
var minCostClimbingStairs = function(cost) {
const dp = []
dp.length = cost.length + 1
dp[0] = 0
dp[1] = 0
for(let i = 2; i<= cost.length; i++) {
dp[i] = Math.min(dp[i -1] + cost[i - 1] , dp[i-2] + cost[i-2])
}
return dp[cost.length]
};
8.买卖股票的最佳时机
给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。
你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。
返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。
var maxProfit = function(prices) {
//为0或者1时, 是没有利润的
let len = prices.length
if( len <= 1 ) return 0
//取得当天之前的最小价格
//用当前价格减去之前最小价格,得到当天最大利润
//与之前最大利润判断,得到最大
let [ min, max ] = [ prices[0], 0 ]
for( let i = 1; i < len; i++) {
max = Math.max( max, prices[i] -min )
min = Math.min( min, prices[i])
}
return max
};
2021/10/27
9.反转链表
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
var reverseList = function(head) {
if(head == null) return null
let [ pre, current ] = [ null, null ]
while(head) {
pre = head.next
head.next = current
current = head
head = pre
}
return current
};
var firstUniqChar = function(s) {
for(let i = 0; i < s.length; i++) {
if(s.lastIndexOf(s[i]) === i && s.indexOf(s[i]) === i) {
return s[i]
}
}
return ' '
};
var majorityElement = function(nums) {
let [ value, n ] = [ 0, 0 ]
for( let i = 0; i < nums.length; i++ ) {
if( n === 0 ) {
value = nums[i]
n++
} else {
value === nums[i] ? n++:n--
}
}
return value
};
var countGoodTriplets = function(arr, a, b, c) {
let n = 0
for( let i = 0; i < arr.length - 2; i++) {
for(let j = i+1; j < arr.length -1 ; j++) {
//continue跳出当前循环,执行平代码,break跳出所有代码
if( Math.abs(arr[i] - arr[j]) > a) continue
for( let k = j+1; k < arr.length; k++) {
if ( Math.abs(arr[j] - arr[k]) > b) continue
if( Math.abs(arr[i] - arr[k]) >c) continue
n++
}
}
}
return n
};
var countQuadruplets = function(nums) {
let count = 0;
for(let i = 0;i < nums.length;i++){
for(let j = i + 1;j < nums.length;j++){
for(let k = j + 1;k < nums.length;k++){
for(let m = k + 1;m < nums.length;m++){
if(nums[i] + nums[j] + nums[k] == nums[m]){
count++;
}
}
}
}
}
return count;
};
var countTriples = function(n) {
if (n == 1) return 0
let count = 0
for(let i = 1; i <= n; i++) {
for( let j = 1; j <= n; j++) {
for( let k = + 1; k <= n; k++) {
if(i*i + j*j == k*k ) {
count++
}
}
}
}
return count
};
//规律题
// 17 8 差9
//25 7 差18
// 99 18 9 差90 由上得,应对9取余,余下的是多次各位相加之和,可是99可能会造成余0, 减一取余之后再加1
var addDigits = function(num) {
return (num - 1)%9 +1
};
var numWaterBottles = function(numBottles, numExchange) {
let count = numBottles
let emptyBottle = numBottles
let rest = 0
while( emptyBottle >= numExchange ) {
count += parseInt(emptyBottle/numExchange)
rest = emptyBottle%numExchange
emptyBottle = parseInt(emptyBottle/numExchange) + rest
}
return count
};
var judgeCircle = function(moves) {
let [u, d, l, r] = [0, 0, 0, 0]
for(let i = 0; i < moves.length; i++) {
if(moves[i] === 'U') {
u++
} else if(moves[i] === 'D') {
d++
} else if (moves[i] === 'L') {
l++
} else {
r++
}
}
if(u === d && l === r) return true
return false
};
var findSpecialInteger = function(arr) {
let total = arr.length
let newArr = []
newArr.length = Math.max(...arr) + 1
for(let i = 0; i < newArr.length; i++) {
newArr[i] = 0
}
for(let i = 0; i < arr.length; i++) {
newArr[arr[i]]++
}
if(Math.max(...newArr)/total > 0.25 ) return newArr.indexOf(Math.max(...newArr))
return -1
};
2021/10/29
var sortSentence = function(s) {
let [ newArr1, newArr2 ] = [ s.split(' '), [] ]
for( let i = 0; i < newArr1.length; i++ ) {
for( let j = 0; j < newArr1.length; j++) {
if( newArr1[j].includes( i + 1 )) {
newArr1[j] = newArr1[j].slice( 0, newArr1[j].length - 1 )
newArr2.push(newArr1[j])
}
}
}
return newArr2.join(" ")
};
var reversePrefix = function(word, ch) {
let len = word.indexOf(ch)
let [ right, left ] = [ len, 0 ]
let arr = word.split('')
while( right > left ) {
[arr[left], arr[right]] = [arr[right], arr[left]]
left++
right--
}
return arr.join('')
};
var replaceSpace = function(s) {
let newStr = ''
for( let i = 0; i < s.length; i++) {
if(s[i] == " ") {
newStr += '%20'
} else {
newStr += s[i]
}
}
return newStr
};
var canBeTypedWords = function(text, brokenLetters) {
let count = 0
text = text.split(' ')
console.log(text)
for( let i = 0; i < text.length; i++ ) {
for ( let j = 0; j <brokenLetters.length; j++) {
if( text[i].includes(brokenLetters[j])) {
count++
break;
}
}
}
count = text.length - count
return count
};
var largestOddNumber = function(num) {
let len = num.length
while( len ) {
if( num[num.length - 1]%2 == 0 ) {
num = num.slice(0, num.length - 1)
} else {
return num
}
}
return " "
};
var shuffle = function(nums, n) {
let [ newArr1, newArr2 ] = [ [], [] ]
let [ even, odd ] = [ 0, 1 ]
newArr1 = nums.splice(0, n)
for( let i = 0; i < n; i++) {
newArr2[even] = newArr1[i]
newArr2[odd] = nums[i]
odd += 2
even += 2
}
return newArr2
};
var restoreString = function(s, indices) {
let newArr = []
newArr.length = indices.length
for( let i = 0; i < indices.length; i++ ) {
newArr[indices[i]] = s[i]
}
return newArr.join('')
};
var finalPrices = function(prices) {
for( let i = 0; i < prices.length + 1; i++ ) {
for( let j = i + 1; j < prices.length; j++ ) {
if( prices[i] >= prices[j] ) {
prices[i] -= prices[j]
break;
}
}
}
return prices
};
var diagonalSum = function(mat) {
let count = 0
for ( let i = 0; i < mat.length; i++) {
for(let j = 0; j < mat[0].length; j++) {
if( i == j || i + j == mat.length - 1 ) {
count += mat[i][j]
}
}
}
//if( mat.length%2 !== 0 ) {
// count -= mat[parseInt(mat.length/2) + 1][parseInt(mat.length/2) +1]
//}
return count
};
var smallerNumbersThanCurrent = function(nums) {
let [ newArr ] = [ [] ]
for ( let i = 0; i < nums.length; i++) {
let count = 0
for( let j = 0; j < nums.length; j++ ) {
if ( i !== j && nums[i] > nums[j] ) {
count++
}
}
newArr.push(count)
}
return newArr
};
var replaceElements = function(arr) {
let max = 0
for ( let i = 0; i < arr.length - 1; i++ ) {
max = Math.max(...arr.slice( i + 1))
arr[i] = max
}
arr[arr.length - 1] = -1
return arr
};
var countNegatives = function(grid) {
let count = 0
for( let i = 0; i < grid.length; i++) {
for( let j = 0; j < grid[i].length; j++) {
if(grid[i][j] < 0) {
count++
}
}
}
return count
};
var canBeEqual = function(target, arr) {
if( target.length !== arr.length ) return false
target.sort((a, b) => a-b)
arr.sort((a, b) => a-b)
for( let i = 0; i < target.length; i++ ) {
if( target[i] !== arr[i] ) {
return false
}
}
return true
};
var findTheDistanceValue = function(arr1, arr2, d) {
let count = 0
for( let i = 0; i < arr1.length; i++ ) {
for ( let j = 0; j < arr2.length; j++ ) {
if(Math.abs(arr1[i] - arr2[j]) <= d) {
count++
break
}
}
}
return arr1.length - count
};
var specialArray = function(nums) {
let newArr = []
let max = Math.max(...nums)
for( let i = 0; i <= max; i++ ) {
newArr[i] = 0
}
for(let i = 0; i < newArr.length; i++) {
for( let j = 0; j < nums.length; j++) {
if(nums[j] >= i) {
newArr[i]++
}
}
}
for(let i = 0; i < newArr.length; i++) {
if( newArr[i] == i ) {
return i
}
}
return -1
};
var areNumbersAscending = function(s) {
s = s.split(' ')
let newArr = []
let count = 0
for( let i = 0; i < s.length; i++ ) {
if(!isNaN(+ s[i])) {
newArr.push(s[i])
}
}
for( let i = 0; i < newArr.length; i++) {
if( parseInt(newArr[i]) >= parseInt(newArr[i +1])) {
count++
}
}
if( count !== 0) return false
return true
};
var stringMatching = function(words) {
let newArr = []
let newArr1 = []
for( let i = 0; i < words.length ; i++) {
for( let j = 0; j < words.length; j++) {
if(words[i].indexOf(words[j]) !== -1 && i !== j) {
newArr.push(words[j])
}
}
}
for( let i = 0; i < newArr.length; i++) {
if(!newArr1.includes(newArr[i])) {
newArr1.push(newArr[i])
}
}
return newArr1
};
var sortArrayByParity = function(nums) {
let [ newArr1, newArr2 ] = [ [], [] ]
for( let i = 0; i < nums.length; i++) {
if( nums[i]%2 === 0 ) {
newArr1.push(nums[i])
} else {
newArr2.push(nums[i])
}
}
return newArr1.concat(newArr2)
};
var sortArrayByParity = function(nums) {
let [ left, right ] = [ 0, nums.length -1 ]
while( left < right ) {
if( nums[left]%2 !== 0 && nums[right]%2 ===0 ) {
[ nums[left], nums[right] ] = [ nums[right], nums[left] ]
left++
right--
} else if( nums[left]%2 !==0 && nums[right]%2 !==0 ) {
right--
} else if( nums[left]%2 === 0 && nums[right]%2 ===0) {
left++
} else if( nums[left]%2 ===0 && nums[right]%2 !==0) {
left++
right--
}
}
return nums
};
var arrayPairSum = function(nums) {
let count = 0
nums.sort((a, b) => a-b)
for(let i = 0; i < nums.length; i++ ){
if( i%2 == 0 ) {
count += nums[i]
}
}
return count
};
var distributeCandies = function(candyType) {
let newArr = []
for( let i = 0; i < candyType.length; i++) {
if(!newArr.includes(candyType[i])) {
newArr.push(candyType[i])
}
}
if(candyType.length/2 < newArr.length) return candyType.length/2
return newArr.length
};
var reverseLeftWords = function(s, n) {
if( n === s.length ) return s
let left = s.slice(0, n)
let right = s.slice(n)
return right + left
};
var calculate = function(s) {
let [ x, y, len ] = [ 1, 0, s.length ]
for ( let i = 0; i < s.length; i++) {
while(len) {
if( s[i] === "A") {
x = 2*x + y
} else {
y = 2*y + x
}
len--
}
}
return x + y
};
var isSumEqual = function(firstWord, secondWord, targetWord) {
let characterSet = {
'a': 0,
'b': 1,
'c': 2,
'd': 3,
'e': 4,
'f': 5,
'g': 6,
'h': 7,
'i': 8,
'j': 9
}
let [ f, s, t ] = [ '', '', '' ]
for( let i = 0; i < firstWord.length; i++) {
f += characterSet[firstWord[i]]
}
for( let i = 0; i < secondWord.length; i++) {
s += characterSet[secondWord[i]]
}
for( let i = 0; i < targetWord.length; i++) {
t += characterSet[targetWord[i]]
}
f = parseInt(f)
s = parseInt(s)
t = parseInt(t)
return f + s === t
};
var makeFancyString = function(s) {
let str = ''
let count = 0
for( let i = 0; i < s.length; i++ ) {
if( s[i+1] == s[i]) {
count++
if(count< 2) {
str += s[i]
}
} else {
str += s[i]
count = 0
}
}
return str
};
var defangIPaddr = function(address) {
address = address.split('.')
return address.join('[.]')
};
var findTheDifference = function(s, t) {
s = s.split('').sort()
t = t.split('').sort()
for ( let i = 0; i < t.length; i++) {
if( s[i] !== t[i]) {
return t[i]
}
}
};
var mergeAlternately = function(word1, word2) {
let [ superflousCharset ,newArr, odd, even ] = [ '', [], 1, 0]
word1.length > word2.length ? superflousCharset = word1.slice( word2.length ) : superflousCharset = word2.slice( word1.length )
let len = word2.length < word1.length ? word2.length : word1.length
for( let i = 0; i < len ; i++ ) {
newArr[even] = word1[i]
newArr[odd] = word2[i]
even += 2
odd += 2
}
return newArr.join('') + superflousCharset
};
var mergeAlternately = function(word1, word2) {
let [ superflousCharset ,str, count ] = [ '','', 0 ]
word1.length > word2.length ? superflousCharset = word1.slice( word2.length ) : superflousCharset = word2.slice( word1.length )
let len = word2.length < word1.length ? word2.length : word1.length
for( let i = 0; i < len ; i++ ) {
str += word1[count]
str += word2[count]
count++
}
return str + superflousCharset
};
2021/11/3 忘记保存,丢失
2021//11/4
47.
var thirdMax = function(nums) {
nums = [...new Set(nums.sort((a, b) => a - b ))]
if(nums.length < 3) return nums[nums.length -1]
return nums[nums.length -3]
};
var exchange = function(nums) {
let [ newArr, newArr1 ] = [ [], [] ]
for( let i = 0; i < nums.length; i++ ) {
if( nums[i]%2 === 0 ) {
newArr.push(nums[i])
} else {
newArr1.push(nums[i])
}
}
return newArr1.concat(newArr)
};
var canMakeArithmeticProgression = function(arr) {
if(arr.length == 2) return true
arr.sort((a, b) => a-b)
for( let i = 0; i < arr.length - 2; i++ ) {
if( arr[i+2] - arr[i+1] !== arr[i+1] - arr[i]) {
return false
}
}
return true
};
var isPowerOfThree = function(n) {
if( n == 1) return true
let x = 3
while( x < n) {
x = 3*x
}
if(x == n) return true
return false
};
var isPowerOfFour = function(n) {
if( n === 1) return true
let x = 4
while( x < n) {
x = 4*x
}
if( x === n) return true
return false
};
var isFlipedString = function(s1, s2) {
if( s1.length !== s2.length) return false
s1 = s1 + s1
if( s1.includes(s2) ) {
return true
}
return false
};
var replaceSpaces = function(S, length) {
let str =''
S = S.split('')
for( let i = 0; i< length; i++) {
if(S[i] === ' ' || S[i] === null) {
str += '%20'
} else {
str += S[i]
}
}
return str
};
var isAnagram = function(s, t) {
if( s.length !== t.length ) return false
if (s === t ) return false
s = s.split('').sort().join()
t = t.split('').sort().join()
if( t === s ) return true
return false
};
var missingNumber = function(nums) {
let len = nums.length
const map = new Map()
for(let i = 0; i<=len; i++) {
map.set(i, i)
}
for(let i = 0; i< nums.length; i++) {
if(map.has(nums[i])) {
map.delete(nums[i])
}
}
return Array.from(map)[0][0]
};
var maximumDifference = function(nums) {
let minValue = nums[1]
let maxDifferenceValue = nums[1] - nums[0]
for( let i = 0; i < nums.length - 1; i++ ) {
minValue = Math.min(minValue, nums[i])
if( maxDifferenceValue < nums[i+1] - minValue ) {
maxDifferenceValue = nums[i+1] - minValue
}
}
if(maxDifferenceValue <= 0) return -1
return maxDifferenceValue
};
var createTargetArray = function(nums, index) {
let target = []
for( let i = 0; i < index.length; i++ ) {
target.splice(index[i], 0, nums[i])
}
return target
};
var checkZeroOnes = function(s) {
let [ curOne, curZero, maxOne, maxZero ] = [ 0, 0, 0, 0 ]
for( let i = 0; i < s.length; i++ ) {
if( s[i] == '1') {
curOne++
curZero = 0
}
if( s[i] == '0' ) {
curZero++
curOne = 0
}
maxOne = Math.max(curOne, maxOne)
maxZero = Math.max(maxZero, curZero)
}
return maxOne > maxZero
};
var majorityElement = function(nums) {
const obj = { }
let [ key1, maxValue ] = [ 0,0 ]
for( let i = 0; i < nums.length; i++ ) {
if( obj[nums[i]] !== undefined) {
obj[nums[i]]++
} else {
obj[nums[i]] = 1
}
}
for( key in obj) {
if( obj[key] > maxValue ) {
key1 = parseInt(key)
maxValue = obj[key]
}
}
return maxValue > parseInt(nums.length/2) ? key1 : -1
};
var minimumAbsDifference = function(arr) {
arr.sort((a, b) => a-b)
let min = arr[1] - arr[0]
for( let i = 1; i < arr.length-1; i++) {
min = Math.min(min, arr[i+1] - arr[i])
}
let arr1 = []
for( let i = 0; i< arr.length - 1; i++ ) {
if( arr[i+1] -arr[i] ==min) {
arr1.push([arr[i], arr[i+1]])
}
}
return arr1
};
var heightChecker = function(heights) {
let nums = [...heights]
for( let i = 0; i < heights.length - 1; i++) {
for( let j = i+1; j < heights.length; j++) {
if( heights[i] > heights[ j]) {
[ heights[i], heights[j]] = [heights[j], heights[i]]
}
}
}
let count = 0
for( let i = 0; i < heights.length; i++ ) {
if( heights[i] !== nums[i]) count++
}
return count
};
//推荐
var heightChecker = function(heights) {
let nums = [...heights]
heights.sort((a, b) => a-b)
let count = 0
for( let i = 0; i < heights.length; i++ ) {
if( heights[i] !== nums[i]) count++
}
return count
};
var relativeSortArray = function(arr1, arr2) {
let [ len, arr, arr3, n ] = [arr2.length, [], [], 0]
for( let i =0; i < arr1.length; i++) {
if(!arr2.includes(arr1[i])) {
arr3.push(arr1[i])
}
}
arr3.sort((a, b) => a-b)
while( len ) {
for( let i = 0; i < arr1.length; i++) {
if( arr1[i] == arr2[n]) {
arr.push(arr1[i])
}
}
n++
len--
}
return [...arr, ...arr3]
};
var maximumProduct = function(nums) {
nums.sort((a, b) => a-b)
let [ max1, max2 , max3, min1, min2] = [ nums[nums.length -1], nums[nums.length -2], nums[nums.length -3], nums[0], nums[1]]
return Math.max(max1*max2*max3, max1*min1*min2)
};
//推荐
var maximumProduct = function(nums) {
let max1 = max2 = max3 = Number.MIN_SAFE_INTEGER//最小安全整数-2*53 -1
let min1 = min2 = Number.MAX_SAFE_INTEGER//最大安全整数 2*53 - 1
for (let val of nums) {
if(val > max1) {
[max1, max2, max3] = [val, max1, max2]
} else if (val > max2) {
[max2, max3] = [val, max2]
} else if (val > max3) {
max3 = val
}
if(val < min1) {
[min1, min2] = [val, min1]
} else if(val < min2) {
min2 = val
}
}
return Math.max(max1*max2*max3, max1*min1*min2)
};
var repeatedNTimes = function(nums) {
const obj = {}
for( let i = 0; i< nums.length; i++ ) {
if( obj[nums[i]] !== undefined) {
obj[nums[i]]++
} else {
obj[nums[i]] = 0
}
}
let [ key1, value] = [ 0, 0]
for ( key in obj ){
if( obj[key] > value ) {
value = obj[key]
key1 = key
}
}
return parseInt(key1)
};
//推荐 set去重属性, 当其中len > set.size(),当即被去掉的是多的那一个
var repeatedNTimes = function(nums) {
let set = new Set()
let len = 0
for(let a of nums){
set.add(a)
len++
if(len > set.size){
return a
}
}
};
var dominantIndex = function(nums) {
if(nums.length == 1 ) return 0
let max1 = max2 = Number.MIN_SAFE_INTEGER
for( let val of nums ) {
if( val > max1 ) {
[ max1, max2 ] = [ val, max1 ]
} else if( val > max2 ) {
max2 = val
}
}
if( parseInt(max1/2) >= max2 ) return nums.indexOf(max1)
return -1
};
var singleNumber = function(nums) {
const obj = {}
for( let i = 0; i < nums.length; i++ ) {
if( obj[nums[i]] !== undefined ) {
obj[ nums[i] ]++
} else {
obj[ nums[i] ] = 0
}
}
for( key in obj ) {
if( obj[key] == '0' ) {
return parseInt(key)
}
}
};
//推荐
var singleNumber = function(nums) {
let a = 0, b = 0;
let c = 100
console.log( c^10)
for (let num of nums) {
b = ~a & (b ^ num);
a = ~b & (a ^ num);
}
return b;
};
var minimumDifference = function(nums, k) {
if( nums.length == 1 || k == 1) return 0
nums.sort((a, b) => a-b)
let min = Number.MAX_SAFE_INTEGER
for( let i = 0; i < nums.length-k+1 ; i++ ) {
for( let j = i+k-1; j < nums.length; j++ ) {
if( nums[j] - nums[i] < min) {
min = nums[j] - nums[i]
}
}
}
return min
};
//推荐
var minimumDifference = function(nums, k) {
nums.sort((a,b)=>a-b);
let res=nums[k-1]-nums[0];
for(let i=1;i<=nums.length-k;i++)
res=Math.min(res,nums[i+k-1]-nums[i]);
return res;
};
nums.sort((a, b) => a-b)
return nums.splice(0, k)
//推荐
var findKthLargest = function (nums, k) {
// 更新小根堆
const sift = (heap, index) => {
let number = heap[index];
for (let i = 2 * index + 1; i < k; i = i * 2 + 1) {
if (heap[i] > heap[i + 1]) i++; // 找到小孩子
if (heap[i] >= number) break;
heap[index] = heap[i];
index = i;
}
heap[index] = number;
};
// 建立堆
const heap = nums.slice(0, k);
for (let i = Math.floor(k / 2) + 1; i >= 0; i--) {
sift(heap, i);
}
// 计算top k
for (let i = k; i <= nums.length - 1; i++) {
if (heap[0] < nums[i]) {
heap[0] = nums[i];
sift(heap, 0);
}
}
return heap[0];
};
var countMatches = function(items, ruleKey, ruleValue) {
let count = 0
for( let i = 0; i < items.length; i++ ) {
if( ruleKey === 'type' ) {
if( items[i][0] == ruleValue) {
count++
}
} else if ( ruleKey == 'color') {
if( items[i][1] == ruleValue ) {
count++
}
} else if( ruleKey == 'name') {
if( items[i][2] == ruleValue) {
count++
}
}
}
return count
};
var diStringMatch = function(s) {
let [ arr, max, min ] = [ [], s.length, 0 ]
for(let i = 0; i<s.length; i++) {
if( s[i] == "D") {
arr.push(max)
max--
}
if( s[i] == "I" ) {
arr.push(min)
min++
}
}
arr.push(min++ || max--)
return arr
};
var canConstruct = function(ransomNote, magazine) {
const obj = {}
const obj1 = {}
for( let i = 0; i < ransomNote.length; i++ ) {
if( obj[ransomNote[i]] !== undefined) {
obj[ransomNote[i]]++
} else {
obj[ransomNote[i]] = 1
}
}
for( let i = 0; i < magazine.length; i++ ) {
if( obj1[magazine[i]] !== undefined) {
obj1[magazine[i]]++
} else {
obj1[magazine[i]] = 1
}
}
for( key in obj) {
if( obj[key] > obj1[key] || obj1[key] == undefined) {
return false
}
}
return true
};
//推荐
var canConstruct = function(ransomNote, magazine) {
//创建一个数组以26个0去填充
var table = new Array(26).fill(0);
for (var i = 0; i < magazine.length; i++) {
table[magazine.codePointAt(i) - 'a'.codePointAt(0)]++;
}
for (var i = 0; i <ransomNote.length; i++) {
table[ransomNote.codePointAt(i) - 'a'.codePointAt(0)]--;
if (table[ransomNote.codePointAt(i) - 'a'.codePointAt(0)] < 0) {
return false;
}
}
return true;
};
var firstUniqChar = function(s) {
const obj = {}
for( let i = 0; i < s.length; i++ ) {
if( obj[s[i]] !== undefined) {
obj[s[i]]++
} else {
obj[s[i]] = 1
}
}
let firstOnceValue = 0
for( key in obj ){
if( obj[key] == 1 ) {
firstOnceValue = key
break
}
}
return firstOnceValue == undefined ? -1 : s.indexOf(firstOnceValue)
};
var squareIsWhite = function(coordinates) {
let arr = coordinates.split('')
if( arr[0].charCodeAt()%2 != 0 ) {
if(arr[1]%2 != 0 ) return false
return true
}
if( arr[0].charCodeAt()%2 == 0 ) {
if( arr[1]%2 !=0 ) return true
return false
}
};
var isPrefixString = function(s, words) {
let str = ''
for( let i = 0 ; i < words.length; i++ ) {
if( s.length > str.length ) {
str += words[i]
} else {
break
}
}
if( str.length > s.length || str.length < s.length) return false
if( str !== s) return false
return true
};
var minStartValue = function(nums) {
let [ now, min ] = [ 0, 0 ]
for( let i = 0; i < nums.length; i++ ) {
(now += num[i] )< min ? min = now : min = min
}
return 1 - min
};
var findPoisonedDuration = function(timeSeries, duration) {
let poisoningTime = 0
for( let i = 0; i < timeSeries.length - 1; i++) {
if(timeSeries[i] + duration > timeSeries[i+1]) {
poisoningTime += timeSeries[i+1] - timeSeries[i]
} else{
poisoningTime += duration
}
}
return poisoningTime + duration
};
var sumOddLengthSubarrays = function(arr) {
//前缀数组
let n = arr.length;
let prefix = new Array(arr.length + 1).fill(0)
for (let i = 0; i < n; i++) {
prefix[i + 1] = prefix[i] + arr[i];
}
let res = 0;
for (let i = 0; i < n; i++) {
for (let j = i; j >= 0; j -= 2) {
res += prefix[i + 1] - prefix[j];
}
}
return res;
};
var uncommonFromSentences = function(s1, s2) {
s1 = s1.split(' ')
s2 = s2.split(' ')
const obj = {}
const obj1 = {}
for( let i = 0; i < s1.length; i++ ) {
if( obj[s1[i]] !== undefined ) {
obj[s1[i]] ++
} else {
obj[s1[i]] = 1
}
}
for( let i = 0; i < s2.length; i++ ) {
if( obj[s2[i]] !== undefined ) {
obj[s2[i]] ++
} else {
obj[s2[i]] = 1
}
}
let arr = []
for( key in obj ) {
if( obj[key] == 1 && obj1[key] == undefined) {
arr.push(key)
}
}
for( key in obj ){
if( obj1[key] == 1 && obj[key] == undefined && !arr.includes(key)) {
arr.push(key)
}
}
return arr
};
var fairCandySwap = function(aliceSizes, bobSizes) {
let aliceSizesValue = aliceSizes.reduce( ( pre, cuurent) => cuurent+= pre)
let bobSizesValue = bobSizes.reduce(( pre, current) => current += pre )
for( let i = 0; i < aliceSizes.length; i++ ) {
for( let j = 0; j < bobSizes.length; j++ ) {
if( aliceSizesValue - aliceSizes[i] + bobSizes[j] == bobSizesValue - bobSizes[j] + aliceSizes[i]) {
return [aliceSizes[i], bobSizes[j]]
}
}
}
};
var toGoatLatin = function(sentence) {
sentence = sentence.split(' ')
for( let i = 0; i < sentence.length; i++ ) {
let s = sentence[i].slice(0, 1).toLocaleLowerCase()
if( s == 'a' || s == 'e' || s == 'i' || s == 'o' || s == 'u') {
sentence[i] = sentence[i] + 'ma'
for( let j = 0; j <= i; j++ ) {
sentence[i] += 'a'
}
} else {
sentence[i] = sentence[i].slice(1) + sentence[i].slice(0, 1) + 'ma'
for( let j = 0; j <= i; j++ ) {
sentence[i] += 'a'
}
}
}
return sentence.join(' ')
};
var findJudge = function(n, trust) {
if( n ==1 && trust.length == 0) return 1
const obj = {}
const obj1 = {}
for( let i = 0; i < trust.length; i++ ) {
if( obj[trust[i][1]] !== undefined ) {
obj[trust[i][1]]++
} else {
obj[trust[i][1]] = 1
}
if( obj1[trust[i][0]] !== undefined ) {
obj1[trust[i][0]]++
} else {
obj1[trust[i][0]] = 1
}
}
let [ xiabiao, value] = [ 0, 0 ]
for( key in obj ) {
if( obj[key] > value ) {
value = obj[key]
xiabiao = key
}
}
if( value == n - 1 && obj1[xiabiao] == undefined ) return parseInt(xiabiao)
return -1
};
2021/11/11
81.
var arrangeCoins = function(n) {
let row = 0
let count = 0
for( let i = 1; i <= n; i++) {
if( n >= row ) {
n -= ++row
count++
} else {
break
}
}
return count
};
var getMaximumGenerated = function(n) {
if( n ==0 ) return 0
let nums = []
nums[0] = 0
nums[1] = 1
for( let i = 2; i <= n; i++ ) {
if( i%2 == 0 ) {
nums[i] = nums[i/2]
} else {
nums[i] = nums[(i-1)/2] + nums[(i-1)/2 + 1]
}
}
let max = Number.MIN_SAFE_INTEGER
for( let i = 0; i < nums.length; i++) {
max < nums[i] ? max = nums[i] : max
}
return max
};
var arrayRankTransform = function(arr) {
const obj = {}
let [ arr1, arr2 ] = [ [], [] ]
arr1 = [...arr]
arr1 = Array.from(new Set(arr1)).sort((a, b) => a-b)
for( let i = 0; i < arr1.length; i++ ) {
if ( obj[arr1[i]] === undefined ) {
obj[arr1[i]] = i+1
}
}
for( let i = 0; i < arr.length; i++) {
arr2[i] = obj[arr[i]]
}
return arr2
};
var getMinDistance = function(nums, target, start) {
let minValue = Number.MAX_SAFE_INTEGER
for( let i = 0; i < nums.length; i++ ) {
if( nums[i] == target && minValue > Math.abs( start - i)) {
minValue = Math.abs(start - i)
}
}
return minValue
};
var findDuplicates = function(nums) {
const obj = {}
let arr = []
for( let i = 0; i < nums.length; i++ ) {
if( obj[nums[i]] !== undefined ) {
obj[nums[i]]++
arr.push(nums[i])
} else {
obj[nums[i]] = 1
}
}
return arr
};
var findDuplicates = function(nums) {
//推荐
// 定义结果集
const res = []
// 遍历数组
for(let i = 0; i < nums.length; i++) {
// 找到每一个元素对应的索引
let index = Math.abs(nums[i]) - 1
// 判断对应元素
if (nums[index] < 0) {
res.push(Math.abs(nums[i]))
}
// 变为相反数
nums[index] = - nums[index]
}
return res
};
var maxSubArray = function(nums) {
let max = Number.MIN_SAFE_INTEGER
let num = Number.MIN_SAFE_INTEGER
for( let i = 0; i < nums.length ;i++ ) {
max = Math.max(nums[i], nums[i] + max)
num = Math.max(num, max)
}
return num
};
次数出现多的题前面,最少类型的量大于人数即可
var halfQuestions = function(questions) {
const obj = {}
let num = questions.length/2
for( let i = 0; i< questions.length; i++ ) {
if( obj[questions[i]] !== undefined ) {
obj[questions[i]]++
} else {
obj[questions[i]] = 1
}
}
let arr = []
for( let key in obj ) {
arr.push(obj[key])
}
let count = 0
let max = 0
arr.sort((a, b) => b-a)
for( let i = 0; i < arr.length; i++) {
if( max < num ) {
max += arr[i]
count++
}
}
return count
};
var majorityElement = function(nums) {
let len = nums.length/3
const obj = {}
for( let i = 0; i< nums.length; i++ ) {
if( obj[nums[i]] !== undefined ) {
obj[nums[i]]++
} else {
obj[nums[i]] = 1
}
}
let arr = []
for( let key in obj ) {
if( obj[key] > len ) {
arr.push( parseInt(key) )
}
}
return arr
};
2021/11/12
88.
var topKFrequent = function(nums, k) {
const obj = {}
for( let i = 0; i < nums.length; i++ ) {
if( obj[nums[i]] !== undefined ) {
obj[nums[i]]++
} else {
obj[nums[i]] = 1
}
}
let arr = []
for( let key in obj ) {
arr.push(obj[key])
}
arr.sort((a, b) => b-a)
let arr1 = []
for( let key in obj ) {
if( obj[key] >= arr[k-1]) {
arr1.push( parseInt(key) )
}
}
return arr1
};
var maximumUnits = function(boxTypes, truckSize) {
for( let i = 0; i < boxTypes.length; i++ ) {
for( let j = 0; j < boxTypes.length; j++ ) {
if( boxTypes[i][1] > boxTypes[j][1] ) {
[ boxTypes[i], boxTypes[j] ] = [ boxTypes[j], boxTypes[i]]
}
}
}
let num = 0
for( let i = 0; i < boxTypes.length; i++ ) {
if(truckSize) {
if( truckSize > boxTypes[i][0] ) {
num += boxTypes[i][0]*boxTypes[i][1]
truckSize -= boxTypes[i][0]
} else {
num += truckSize*boxTypes[i][1]
truckSize = 0
}
}
}
return num
};
//推荐(优化)
var maximumUnits = function(boxTypes, truckSize) {
boxTypes.sort((a,b)=>b[1]-a[1]);
let num = 0
for( let i = 0; i < boxTypes.length; i++ ) {
if(truckSize) {
if( truckSize > boxTypes[i][0] ) {
num += boxTypes[i][0]*boxTypes[i][1]
truckSize -= boxTypes[i][0]
} else {
num += truckSize*boxTypes[i][1]
truckSize = 0
}
}
}
return num
};
var search = function(nums, target) {
const obj = {}
for( let i = 0; i < nums.length; i++ ) {
if( obj[nums[i]] !== undefined ) {
obj[nums[i]]++
} else {
obj[nums[i]] = 1
}
}
return obj[target] == undefined ? 0: obj[target]
};
var searchRange = function(nums, target) {
if( nums.length == 0) return [-1, -1]
for( let i = 0; i < nums.length; i++ ) {
if(nums.indexOf(target) !== undefined && nums.lastIndexOf(target) !== undefined) {
return [nums.indexOf(target), nums.lastIndexOf(target)]
} else {
return [ -1, -1]
}
}
};
var kLengthApart = function(nums, k) {
let zero = 0
let arr = []
for( let i = 0; i < nums.length; i++ ) {
if( nums[i] == 0 && i != 0 ) {
zero++
} else if( nums[i] == 1){
arr.push(zero)
zero = 0
}
}
if( arr[0] == 0) arr.shift()
let count = 0
for( let i = 0; i < arr.length; i++ ) {
if( arr[i] < k ) {
count++
}
}
return count == 0 ? true : false
};
var maxProfit = function(prices) {
let minPrices = prices[0]
let maxProfit = 0
for( let i = 1; i < prices.length; i++ ) {
minPrices = (minPrices > prices[i] ? prices[i]: minPrices)
maxProfit = (maxProfit > (prices[i] - minPrices)? maxProfit : prices[i] - minPrices)
}
return maxProfit
};
//推荐(子集写应该会用到其他的,我对位运算并不是很熟)
var singleNumber = function(nums) {
let a = 0
let b = 0D
console.log(10 ^ 9)
for( let key in nums ) {
a = (a ^ nums[key]) & ~b
b = (b ^ nums[key]) & ~a
}
return a
};
2021/11/13
95.
var numColor = function(root) {
const set = new Set()
dff(root)
return set.size
function dff(root) {
if( root !== null ) {
set.add(root.val)
dff( root.left)
dff( root.right)
}
}
};
var duplicateZeros = function(arr) {
for( let i = 0; i < arr.length; i++) {
if( arr[i] == 0) {
arr.pop()
arr.splice( i , 0, 0)
i = i + 1
}
}
return arr
};
2021/11/14
97.
//推荐
var isMonotonic = function(nums) {
let asc = true, desc = true;
for(let i=0; i<nums.length-1 && (asc || desc); i++) {
asc = asc && nums[i] <= nums[i+1];
desc = desc && nums[i] >= nums[i+1];
}
return (asc || desc)
};
var flipAndInvertImage = function(image) {
for( let i = 0;i < image.length; i++ ) {
image[i] = image[i].reverse()
for( let j = 0; j < image[i].length; j++ ) {
image[i][j] = !image[i][j]
}
}
return image
};
var leastMinutes = function(n) {
let count = 0
let num = 1
while( num < n ) {
num *= 2
count++
}
return count + 1
};
var slowestKey = function(releaseTimes, keysPressed) {
let arr = []
releaseTimes.unshift(0)
for( let i = 1; i <releaseTimes.length; i++ ) {
arr[i-1] = releaseTimes[i] - releaseTimes[i-1]
}
let max = Math.max(...arr)
let arr1 = []
for( let i = 0; i < arr.length; i++ ) {
if(arr[i] == max) {
arr1.push( i )
}
}
let maxValue = keysPressed.slice( arr1[0], arr1[0]+1)
for( let i = 0; i < keysPressed.length; i++ ) {
for( let j = 1; j < arr1.length; j++ ) {
if( maxValue.charCodeAt() < keysPressed[arr1[j]].charCodeAt() ) {
maxValue = keysPressed[arr1[j]]
}
}
}
return maxValue
};
//推荐
var slowestKey = function (releaseTimes, keysPressed) {
let res = keysPressed[0];
let max = releaseTimes[0];
for (let i = 1; i < keysPressed.length; i++) {
const d = releaseTimes[i] - releaseTimes[i - 1];
if (d > max) {
res = keysPressed[i];
max = d;
} else if (d === max && keysPressed[i] > res) {
res = keysPressed[i];
}
}
return res;
};
var canPlaceFlowers = function(flowerbed, n) {
let count = 0
for( let i = 0; i < flowerbed.length; i++ ) {
if( flowerbed[i] == 0 && flowerbed[i-1] !== 1 && flowerbed[i+1] !== 1) {
flowerbed[i] = 1
count++
}
}
return count >= n
};
2021/11/15
102.