Given an array of ints, return true if there is a 1 in the array with a 2 somewhere later in the array.
has12({1, 3, 2}) → true
has12({3, 1, 2}) → true
has12({3, 1, 4, 5, 2})-->true
Answer:
public boolean has12(int[] nums) {
int count=0;
int count1=0;
int count2=0;
for(int i=0;i<nums.length;i++){
if(nums[i]==1){count++;count1=i;}
if(nums[i]==2){count++;count2=i;}
}
return (count>1)&&(count1<count2)?true:false;
}
has12({1, 3, 2}) → true
has12({3, 1, 2}) → true
has12({3, 1, 4, 5, 2})-->true
Answer:
public boolean has12(int[] nums) {
int count=0;
int count1=0;
int count2=0;
for(int i=0;i<nums.length;i++){
if(nums[i]==1){count++;count1=i;}
if(nums[i]==2){count++;count2=i;}
}
return (count>1)&&(count1<count2)?true:false;
}
No comments:
Post a Comment