題目:
Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
中文意思:
就是看看所給的數(shù)組中有沒(méi)有重復(fù)的數(shù)字。若有,返回true。若無(wú),返回false。
javascript代碼:
var containsDuplicate = function(nums) {
var flag = [0];
for(var x of nums){
if(typeof(flag[x]) == 'undefined'){
flag[x] = 0;
}
flag[x]++;
if(flag[x] > 1){
return true;
}
}
return false;
};
一年前的java代碼:
public class Solution {
public boolean containsDuplicate(int[] nums) {
if(nums.length < 2){
return false;
}else{
Set<Integer> set = new HashSet<Integer>();
set.add(nums[0]);
for(int i = 1; i < nums.length; i++){
if(set.contains(nums[i])){
return true;
}else{
set.add(nums[i]);
}
}
return false;
}
}
}
發(fā)現(xiàn)對(duì)javascript基本的使用知識(shí)、語(yǔ)法啥的知道的太少。。要惡補(bǔ)了。
還有, 要形成代碼塊,是要空一行再縮進(jìn)??
1: for...of...與for...in...區(qū)別
比如:
//var arr = ['test0', 'test1', 'test2'];
for(var x in arr) {console.log(x) //x = 0, 1, 2...}
for(var x of arr) {console.log(x) //x ='test0', 'test1', 'test2'...}