217. Contains Duplicate

題目:
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'...}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容