//1.isPopOrder
public Boolean isPopOrder(int[] aNums, int[] bNums) {
if (aNums == null || bNums == null||aNums.length!=bNums.length ) {
return false;
}
int len=aNums.length;
Stack<Integer> sk = new Stack<Integer>();
int ai = 0;
int bi = 0;
while (bi < len) {
if (ai==len) {return false;}
int bAns=bNums[bi];
//aNums[ai] dynamic add
if (sk.size() == 0) {
sk.push(aNums[ai]);
ai++;
}
while (ai < len) {
//here use peek
if (sk.peek()!= bValue) {
sk.push(aNums[ai]);
ai++;
} else {
break;
}
}
sk.pop();//here use pop
bi++;
}
if (sk.isEmpty() && ai == len && bi == len) {return true;}
return false;
}
//2.reverseInt
public int reverse(int n) {
//minValue can not be -minValue
if (n == Integer.MIN_VALUE) {return 0;}
if (n < 0) {return -reverse(-n);}
int ans=0;
while (n != 0) {
//may exceed the max
if (ans > Integer.MAX_VALUE / 10) {return 0;}
ans=ans * 10 + n % 10;n = n / 10;
}
return ans;
}
//3. isDuplicated in 1-n
public Boolean isDuplicated(int[] nums) {
if (nums == null || nums.length == git 0) {return false;}
for (int i = 0; i < nums.length; i++) {
while (nums[i] != i) {
if (nums[i] == nums[nums[i]]) {return true;}
int temp = nums[i];nums[i] = nums[nums[i]];nums[nums[i]] =temp;
}
}
return defaultFlag;
}
网友评论