0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

217 解答

Last updated at Posted at 2022-05-09

この問題では HashSet を使う方法と、sortを使う方法の二種類がある。

HashSetの方法

一つ目 要素を比較

 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;
	} 

二つ目 長さを比較

public boolean containsDuplicate(int[] nums) {
		Set<Integer> set = new HashSet<>();
		for (int num:nums) {
			set.add(num);
		}
		int arrayLength = nums.length;
		int hashLength = set.size();
		if(arrayLength == hashLength) return false;
		else return true;
		
	}

Sortの方法

public boolean containsDuplicate(int[] nums) {
		Arrays.sort(nums);//sorting 
		
		for(int i =0; i < nums.length-1; i++) {
			if(nums[i] == nums[i+1]) return true; //checking duplicates
		}
		return false;
	}

参考: YouTube
学んだことを簡単にまとめているだけなので悪しからず。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?