How can I find a number which occurs an odd number of times in a SORTED array in O(n) time?

后端 未结 15 2170
梦如初夏
梦如初夏 2021-01-30 10:31

I have a question and I tried to think over it again and again... but got nothing so posting the question here. Maybe I could get some view-point of others, to try and make it w

15条回答
  •  不要未来只要你来
    2021-01-30 11:13

    AHhh. There is an answer.

    Do a binary search and as you search, for each value, move backwards until you find the first entry with that same value. If its index is even, it is before the oddball, so move to the right.
    If its array index is odd, it is after the oddball, so move to the left.

    In pseudocode (this is the general idea, not tested...):

        private static int FindOddBall(int[] ary)
        {
            int l = 0,
                r = ary.Length - 1;
            int n = (l+r)/2;
            while (r > l+2)
            {
                n = (l + r) / 2;
                while (ary[n] == ary[n-1])
                    n = FindBreakIndex(ary, l, n);
                if (n % 2 == 0) // even index we are on or to the left of the oddball 
                    l = n;
                else            // odd index we are to the right of the oddball
                    r = n-1;
            }
            return ary[l];
        }
        private static int FindBreakIndex(int[] ary, int l, int n)
        {
            var t = ary[n];
            var r = n;
            while(ary[n] != t || ary[n] == ary[n-1])
                if(ary[n] == t)
                {
                    r = n;
                    n = (l + r)/2;
                }
                else
                {
                    l = n;
                    n = (l + r)/2;
                }
            return n;
        }
    

提交回复
热议问题