美文网首页
217. Contains Duplicate

217. Contains Duplicate

作者: 艾石溪 | 来源:发表于2016-11-22 21:04 被阅读8次

题目:
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.

中文意思:
就是看看所给的数组中有没有重复的数字。若有,返回true。若无,返回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;
        }
    }
 }

发现对javascript基本的使用知识、语法啥的知道的太少。。要恶补了。
还有, 要形成代码块,是要空一行再缩进??

1: for...of...与for...in...区别
比如:

    //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'...}

相关文章

网友评论

      本文标题:217. Contains Duplicate

      本文链接:https://www.haomeiwen.com/subject/wcrmpttx.html