コード例 #1
0
ファイル: A702.cs プロジェクト: kunge0726/LeetCode
 public int Search(ArrayReader reader, int target)
 {
     int left = 0;
     int right = 1;
     while(reader.get(right) < target)
     {
         left = right;
         right <<= 1;
     }
     while(left <= right)
     {
         var mid = left + ((right - left) >> 1);
         var temp = reader.get(mid);
         if (temp == target)
         {
             return mid;
         }
         else if (temp < target)
         {
             left = mid + 1;
         }
         else
         {
             right = mid - 1;
         }
     }
     return -1;
 }
コード例 #2
0
        /**
         * @param reader: An instance of ArrayReader can read number by index.
         * @param target: An integer
         * @return : An integer which is the index of the target number
         */

        public int SearchBigSortedArray(ArrayReader reader, int target)
        {
            // Algorithm:
            // 1. get the index that ArrayReader.get(index) >= target in
            //    O(logk)
            // 2. Binary search the target between 0 and index
            int index = 1;

            while (reader.get(index - 1) < target)
            {
                index = index * 2;
            }
            int start = 0, end = index - 1;

            while (start + 1 < end)
            {
                int mid = start + (end - start) / 2;
                if (reader.get(mid) < target)
                {
                    start = mid;
                }
                else
                {
                    end = mid;
                }
            }
            if (reader.get(start) == target)
            {
                return(start);
            }
            if (reader.get(end) == target)
            {
                return(end);
            }
            return(-1);
        }