var majorityElement = function (nums) { let newObj = {} for (let num of nums) { // console.log(num) (!newObj[num]) ? newObj[num] = 1 : newObj[num]++ } // console.log(newObj) let nNum = nums.length / 2 // console.log('nNum', nNum) for (let key in newObj) { if (newObj[key] > nNum) return key }
for (let num of nums) { if (candidate1 === num) count1++; elseif (candidate2 === num) { count2++; } } if (count1 > limit) res.push(candidate1) if (count2 > limit) res.push(candidate2) console.log(res, count1, count2) return res
Given an array, rotate the array to the right by k steps, where k is non-negative.
Example 1:
1 2 3 4 5 6
Input: nums = [1,2,3,4,5,6,7], k = 3 Output: [5,6,7,1,2,3,4] Explanation: rotate 1 steps to the right: [7,1,2,3,4,5,6] rotate 2 steps to the right: [6,7,1,2,3,4,5] rotate 3 steps to the right: [5,6,7,1,2,3,4]
1 2 3 4 5 6 7
Example 2:
Input: nums = [-1,-100,3,99], k = 2 Output: [3,99,-1,-100] Explanation: rotate 1 steps to the right: [99,-1,-100,3] rotate 2 steps to the right: [3,99,-1,-100]
1.由上述範例可以觀察到,根據 k 值進行抓取最後的元素至最前面,以此類推下去。 當 k 為某值的時後,會由陣列最後方取的該數目元素。 以下為直覺解法:
1 2 3 4 5 6 7 8 9 10 11
//會有 問題:Time Limit Exceeded const rotateArray1 = function (nums, k) { //unshift 將給入的元素值放到最前面 for (let i = 0; i < k; i++) { console.log('nums.pop()', nums.pop()) nums.unshift(nums.pop()); } console.log('num', nums) return nums; }
題目: Given a string s containing just the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘ and ‘]’, determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Every close bracket has a corresponding open bracket of the same type.
var isValid = function (s) { const hashMap = { "(": ")", "{": "}", "[": "]" }; const stack = []; for (let ch of s) { if (hashMap[ch]) { // ch is an opening bracket stack.push(hashMap[ch]); } elseif (stack.length > 0 && stack[stack.length - 1] === ch) { //當空陣列裡面有值且陣列的最後一個值和 key 是一樣的就從陣列中刪除 // ch is a closing bracket and top of stack matches stack.pop(); } else { // ch is a closing bracket and top of the stack doesn't match returnfalse; } } return stack.length === 0; };
Welcome to Hexo! This is your very first post. Check documentation for more info. If you get any problems when using Hexo, you can find the answer in troubleshooting or you can ask me on GitHub.