665. non-decreasing-array
- Runtime: 1 ms, faster than 99.48% of Java online submissions for Non-decreasing Array.
- 이 문제 조금 어렵네요
- for문 한번돌리려고 했는데 너무 로직이 복잡해서 2번돌리는걸로
class Solution {
public boolean checkPossibility(int[] nums) {
if(nums.length <= 2){
return true;
}
int count =0;
boolean pre = true;
boolean after = true;
for(int i=0; i<nums.length-1; i++){
if(nums[i] <= nums[i+1]){
}else{
if(count >0){
pre = false;
break;
}
count++;
if(i >0){
if(nums[i-1] >nums[i+1]){
pre= false;
break;
}
}
}
}
count =0;
for(int i=0; i<nums.length-1; i++){
if(nums[i] <= nums[i+1]){
}else{
if(count >0){
after = false;
break;
}
count++;
if(i+2 <nums.length){
if(nums[i] >nums[i+2]){
after= false;
break;
}
}
i++;
}
}
return (pre || after);
}
}
public class Solution {
public boolean checkPossibility(int[] nums) {
if(nums.length <= 2){
return true;
}
int count =0;
for(int i=0; i<nums.length-1; i++){
if(nums[i] > nums[i+1]){
if(count++ >0) return false;
if(i >0){
if(nums[i-1] <=nums[i+1]){
nums[i-1] = nums[i];
continue;
}
}
if(i+2 <nums.length){
if(nums[i]<=nums[i+2]){
nums[i+1] = nums[i];
continue;
}else{
if(i>0){
return false;
}
}
}
}
}
return true;
}
}
No comments:
Post a Comment