刷题是一方面,另一方面是熟悉js的特性
Detect Capital
Description
Given a word, you need to judge whether the usage of capitals in it is right or not.
We define the usage of capitals in a word to be right when one of the following cases holds:
1.All letters in this word are capitals, like "USA".
2.All letters in this word are not capitals, like "leetcode".
3.Only the first letter in this word is capital, like "Google".
Otherwise, we define that this word doesn't use capitals in a right way.
Solution1
var detectCapitalUse = function(word) {
if(word.length==1){
return true
}
else {
if(word.charCodeAt(0)>96){
for(let i=1;i<word.length;i++){
if (word.charCodeAt(i)<91){return false}
}
}
else{
if(word.length==2){
return true
}else if(word.charCodeAt(1)>96){
for(let i=2;i<word.length;i++){
if (word.charCodeAt(i)<91){return false}
}
}else{
for(let i=2;i<word.length;i++){
if (word.charCodeAt(i)>96){return false}
}
}
}
return true
}
};
如无意外循环请用let,节省空间
Solution2
var detectCapitalUse = function(word) {
if (word.toLowerCase() === word) return true;
if (word.toUpperCase() === word) return true;
if (word[0].toUpperCase() + word.slice(1).toLowerCase() === word) return true;
return false;
};
虽然不是跑起来最快的,但是写起来是最快的。
Tips
.charCode是键盘事件,charcodeAt(index)是作用在数组上的
Find All Duplicates in an Array
Description
Given an array of integers, 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements that appear twice in this array.
Could you do it without extra space and in O(n) runtime?
Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[2,3]
Solution1
var findDuplicates = function(nums) {
result = []
htable = new Array(nums.length)
nums.forEach((item)=>{
if(htable[item]) result.push(item) ;
else htable[item] =1;
})
return result
};
直接想到的,不算是hash,就是个计数器
Solution2
var findDuplicates = function(nums) {
const result = []
for (let i = 0; i < nums.length; i++){
const index = Math.abs(nums[i]) - 1
if (nums[index] < 0){
result.push(index + 1)
}
nums[index] = -nums[index]
}
return result
};
这是看到的别人的解法,第一眼看上去挺惊艳的,满足了无新空间以及O(n)时间复杂度,仔细一想和我的解法差不多,就是将计数器放在原址上,不过设计还是很巧妙,值得学习。
网友评论