C# solution: bucket sort


  • 0
    B
    public class Solution 
    {
        public int FindDuplicate(int[] nums) 
        {
    
            for (int i = 0; i < nums.Length; i++)
            {
                while(nums[i] - 1 != i)
                {
                    var tempIndex = nums[i] - 1;
                    if (nums[tempIndex] == nums[i]) break;
                    nums[i] = nums[tempIndex];
                    nums[tempIndex] = tempIndex + 1;
                }
            }
    
            for (int i = 0; i < nums.Length; i++)
            {
                if (i != nums[i] - 1)
                {
                    return nums[i];
                }
            }
    
            throw new Exception("Never reach");
    
        }
    }
    

Log in to reply
 

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