Simple C# solution


  • 0
    T
    public class Solution
        {
            int[] nums;
            Random rand;
    
            public Solution(int[] nums)
            {
                this.nums = nums;
                rand = new Random();
            }
    
            public int pick(int target)
            {
                for (int i = 0; i < this.nums.Length; i++)
                {
                    if (nums[i] != target)
                    {
                        continue;
                    } 
                    else
                    {
                        int minIndex = i;
                        int maxIndex = i;
    
                        while(true)
                        {
                            if (maxIndex < nums.Length && nums[maxIndex] == target)
                            {
                                maxIndex++;
                            }
                            else
                            {
                                break;
                            }
                        }
    
                        return rand.Next(minIndex, maxIndex);
                    }
                }
    
                return -1;
            }
        }
    

Log in to reply
 

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