#include<iostream> bool is_in_array(int* begin, int* end, int target){ int mid = (end - begin)/2; if(*begin>target || *end<target) //value has to be between [begin,end] return false; // to continue if(begin[mid] == target) return true; if(begin[mid] > target) //look at the left subarray return is_in_array(begin,begin+mid-1,target); // (begin[mid] < target) look at the right subarray return is_in_array(begin+mid+1,end,target); } bool find_in_array(int arr[] ,int target,int size){ int* begin = arr; int* end = begin+size-1; bool result = is_in_array(begin,end,target); return result; } void test_is_in_array(bool expected, int arr[],int target,int size){ bool result = find_in_array(arr,target,size); std::cout<<(result==expected?"PASS: ":"FAIL: ") <<" result => "<<result<<" expected =>" <<expected<<std::endl; } int main( void ){ int arr1[] = {1,3,5,7,9,10}; int arr2[] = {1,3,7,9,10}; int arr3[] = {1,3,5,7,9,10,11,15,16,16,16,16,16,19,20}; int arr4[] = {1,3,5,7,9,10,15,20,25,50,1000,1000001}; int arr5[] = {1,3,5,7,9,10,11,12,13,14}; test_is_in_array(0,arr1,0,sizeof(arr1)/sizeof(*arr1)); test_is_in_array(1,arr2,7,sizeof(arr2)/sizeof(*arr2)); test_is_in_array(1,arr3,16,sizeof(arr3)/sizeof(*arr3)); test_is_in_array(1,arr4,50,sizeof(arr4)/sizeof(*arr4)); test_is_in_array(0,arr5,15,sizeof(arr5)/sizeof(*arr5)); test_is_in_array(1,arr5,14,sizeof(arr5)/sizeof(*arr5)); return 0; }
Given an array with n integers, your task is to check if it could become non-decreasing by modifying at most 1 element.We define an array is non-decreasing if array[i] <= array[i + 1] holds for every i (1 <= i < n). Example 1: Input: [4,2,3] Output: True Explanation: You could modify the first 4 to 1 to get a non-decreasing array. Example 2: Input: [4,2,1] Output: False Explanation: You can't get a non-decreasing array by modify at most one element. Note: The n belongs to [1, 10,000]. Source: LeetCode At first glance, it looks like an easy and straightforward problem, but believe me it's greedy problem. In the problem, you are allowed to make atmost "one" modification to make a non-decreasing array. Nondecreasing means that every element is greater than or equal to the one before it e.g. [1,3,4,4,5,6,9]. For example, [2,2,3,2,4] can this become non-decreasing? Yes, by replacing 3 with 2 =>[2,2,2,2,4]. What about this:
Comments
Post a Comment