Given an array of n integers nums, a 132 pattern is a subsequence of three integers nums[i], nums[j] and nums[k] such that i < j < k and nums[i] < nums[k] < nums[j].
Return true if there is a 132 pattern in nums, otherwise, return false. `
class Solution
{
public boolean find132pattern(int[] nums)
{
int l = 0;
int r = 2;
while (r < nums.length)
{
int mid=(l+r)/2;
if (nums[l] < nums[r])
{
if (nums[mid]>nums[r])
{
return true;
}
}
l++;
r++;
}
return false;
}
}
This is my solution. if there is a logical error, could you possibly assist me in solving this?
The issue with your program is that only the very start has to be
true.return [value]will end the method, meaning if the start or one part is true, but the rest isfalse, your program will still returntruebecause it found one part in a "132" format. Rather than returningtruein yourwhileloop, you could try returningfalse:This ensures that if any part of the array's condition is false that it will not give a "false positive".
Alternatively you could add a counter like so:
This makes sure the condition was always
true. An even more streamlined version of both these methods, however, would likely just be to do this:This immediately checks if the condition is
truewithout the need for anifstatement or really anything else.Results of each:
I hope this helped!