#力扣 LeetCode575. 分糖果 @FDDLC
阿新 • • 發佈:2021-01-07
技術標籤:演算法&資料結構
題目描述:
https://leetcode-cn.com/problems/distribute-candies/
Java程式碼:
import java.util.HashSet; class Solution { //給定一個偶數長度的陣列 public int distributeCandies(int[] candyType) { HashSet<Integer> set=new HashSet<>(); for(int c:candyType)set.add(c); return Math.min(set.size(),candyType.length/2); } }
Java程式碼二:
import java.util.HashSet; class Solution { //給定一個偶數長度的陣列 public int distributeCandies(int[] candyType) { HashSet<Integer> set=new HashSet<>(); int halfLen=candyType.length/2,count=0; for(int c:candyType){ if(set.add(c)){ count++; if(count>=halfLen)return halfLen; } } return count; } }
Java程式碼三:
import java.util.HashSet; class Solution { //給定一個偶數長度的陣列 public int distributeCandies(int[] candyType) { boolean[] a=new boolean[200001]; int halfLen=candyType.length/2,count=0; for(int c:candyType){ if(a[c+100000]==false){ a[c+100000]=true; count++; if(count>=halfLen)return halfLen; } } return count; } }
Java程式碼四:
import java.util.HashSet;
class Solution { //給定一個偶數長度的陣列
public int distributeCandies(int[] candyType) {
boolean[] a=new boolean[200001];
int halfLen=candyType.length/2,count=0,tmp;
for(int c:candyType){
tmp=c+100000;
if(a[tmp]==false){
a[tmp]=true;
count++;
if(count>=halfLen)return halfLen;
}
}
return count;
}
}