896. Monotonic Array
1. Description
An array is monotonic if it is either monotone increasing or monotone decreasing.
An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all i <= j, A[i] >= A[j].
Return true if and only if the given array A is monotonic.
2. Example
Example 1:
Input: [1,2,2,3]
Output: true
Example 2:
Input: [6,5,4,4]
Output: true
Example 3:
Input: [1,3,2]
Output: false
Example 4:
Input: [1,2,4,5]
Output: true
Example 5:
Input: [1,1,1]
Output: true
3. Note
- 1 <= A.length <= 50000
- -100000 <= A[i] <= 100000
4. Solutions
My Accepted Solution
n = i_nums.size()
Time complexity: O(n)
Space complexity: O(1)
class Solution
{
public:
// bool isMonotonic(vector<int>& A)
bool isMonotonic(vector<int> &i_nums)
{
if(i_nums.size() == 1) return true;
int increaseArray = 0;
for(int i = 0; i < i_nums.size() - 1; i++)
{
if(increaseArray == 0 && i_nums[i] != i_nums[i+1])
{
increaseArray = i_nums[i] < i_nums[i+1] ? 1 : -1;
continue;
}
if(i_nums[i] < i_nums[i+1] && increaseArray == -1 || i_nums[i] > i_nums[i+1] && increaseArray == 1)
{
return false;
}
}
return true;
}
};
4.1 One Loop
n = i_nums.size()
Time complexity: O(n)
Space complexity: O(1)
class Solution
{
public:
bool isMonotonic(vector<int> &i_nums)
{
bool increase = true, decrease = true;
for (int i = 0; i < i_nums.size() - 1; ++i)
{
if (i_nums[i] > i_nums[i + 1])
{
increase = false;
}
if (i_nums[i] < i_nums[i + 1])
{
decrease = false;
}
}
return increase || decrease;
}
};