Thursday, 29 July 2021

Contains Duplicate - LeetCode 217

 Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.


Example 1:

Input: nums = [1,2,3,1]
Output: true

Example 2:

Input: nums = [1,2,3,4]
Output: false

Example 3:

Input: nums = [1,1,1,3,3,4,3,2,4,2]
Output: true

Solution:

import java.io.*;

import java.util.*;

public class Main

{

    static Scanner sc=new Scanner(System.in);

public static void main(String[] args) {

    

    int n;

    n=sc.nextInt();

    int[] arr=new int[n];

    for(int i=0;i<n;i++){

        arr[i]=sc.nextInt();

    }

    Solution s=new Solution();

    boolean res=s.containsDuplicate(arr);

    System.out.println(res);

}

}


public class Solution {

  

   public boolean containsDuplicate(int[] nums) {

        

        HashSet<Integer> hashset = new HashSet<>();

        

        for(int i=0;i<nums.length;i++){

            if(hashset.contains(nums[i]))

                return true;

            

            hashset.add(nums[i]);

        }

        

        return false;

    }

}


Your input
[1,2,3,1]
Output
true
Expected
true

No comments:

Post a Comment

Random password generator in Java

       Random password generator in Java Source code: mport java.io.*; import java.util.*; public class Main { public static void main(Str...