1.题目
2.解答
class Solution {
public List<String> buildArray(int[] target, int n) {
List<String> list = new ArrayList<>();
boolean flag = false;
int count = 0;
for(int i = 1; i <= n; i++){
if(binarySearch(target, i)){
list.add("Push");
// 如果已经满足target数组长度,就退出
if(++count == target.length){
break;
}
} else{
list.add("Push");
list.add("Pop");
}
}
return list;
}
// 因为是有序的,所以使用二分查找法
public boolean binarySearch(int[] target, int i){
int low = 0, high = target.length - 1;
while(low <= high){
int mid = low + (high - low) / 2;
if(target[mid] == i){
return true;
}else if(target[mid] > i){
high = mid -1;
} else{
low = mid + 1;
}
}
return false;
}
}
从O(n^2)-----到O(nlogn)的时间复杂度