1304. 和爲零的N個唯一整數
class Solution {
public int[] sumZero(int n) {
int [] res = new int[n];
for(int i=0;i<n/2;i++){
res[i * 2]=i+1;
res[i * 2 + 1]=-(i+1);
}
return res;
}
}
1305. 兩棵二叉搜索樹中的所有元素
一開始想複雜了,參考了別人寫的代碼,用了優先隊列,降低了難度
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> getAllElements(TreeNode root1, TreeNode root2) {
PriorityQueue<Integer> priorityQueue = new PriorityQueue<Integer>();
getOneRoot(root1,priorityQueue);
getOneRoot(root2,priorityQueue);
List<Integer> lists = new ArrayList<Integer>();
while(!priorityQueue.isEmpty()){
lists.add(priorityQueue.poll());
}
return lists;
}
public void getOneRoot(TreeNode root,PriorityQueue<Integer> priorityQueue){
if(root==null){
return;
}
priorityQueue.offer(root.val);
getOneRoot(root.left,priorityQueue);
getOneRoot(root.right,priorityQueue);
}
}
1306. 跳躍遊戲 III
這個題目一看肯定是想到要用廣度遍歷,然後另外一點就是使用一個數字標記該點是否被訪問過,因爲如果訪問過,再訪問這個點,走的路徑是一樣的,所以沒必要再訪問它,直接return就好了。
class Solution {
int length = 0;
boolean [] visited;
public boolean canReach(int[] arr, int start) {
length = arr.length;
visited = new boolean[length];
bfs(arr,start);
for(int i=0;i<length;i++){
if(arr[i]==0){
if(visited[i]==true){
return true;
}
}
}
return false;
}
public void bfs(int [] arr, int curr){
if(visited[curr]==true){
return;
}
visited[curr]=true;
if(arr[curr]==0){
return;
}
if((curr+arr[curr]>=0 )&& (curr+arr[curr]<length)){
bfs(arr,curr+arr[curr]);
}
if((curr-arr[curr]>=0 )&& (curr-arr[curr]<length)){
bfs(arr,curr-arr[curr]);
}
return;
}
}
最後一道困難的題目,有空的時候我再撿起來做一下,這裏偷個懶。