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.

中文意思:
就是看看所给的数组中有没有重复的数字。若有,返回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'...}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容