This problem is tricky, since c++ truncates an integer to zero but not to bottom! Help!


  • 0
    P

    This is my code, it takes me some time to figure out the correct return statement. Can anybody give me some advice? I think it's due to c++ truncate an integer to zero, but this problem treat -1 as an index.

    int findPeakElement(vector<int>& nums) {
    int p = -1, q = nums.size(), mid, mid1, mid2;
    while (p < q - 2) {
        mid = (p+q)/2;
        mid1 = (p+mid)/2;
        mid2 = (mid+q)/2;
        if (nums[mid1] > nums[mid]) {
            q = mid;
        } else if (nums[mid2] > nums[mid]) {
            p = mid;
        } else {
            p = mid1;
            q = mid2;
        }
    }
    return p == q-1 && p == 0 ? 0 : (p+q)/2;
    }

Log in to reply
 

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