2 solutions base on 1 idea: efficient way, or less line way :D


  • 1

    #1 It's not necessary to go through whole array

        public int DistributeCandies(int[] candies) {
            HashSet<int> dic = new HashSet<int>();
            foreach(int i in candies)
            {
                if(!dic.Contains(i))
                {
                    dic.Add(i);
                    if(dic.Count == candies.Length/2) return dic.Count;
                }
            }
            return dic.Count;
        }
    
    
    #2 One line solution
    
    public int DistributeCandies(int[] candies) {
        return candies.Distinct().ToArray().Length > candies.Length/2 ? candies.Length/2 : candies.Distinct().ToArray().Length;
    }

  • 0
    O

    Very nice of this:

    if(dic.Count == candies.Length/2) return dic.Count;

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.