54. 螺旋矩阵【中等】
https://leetcode-cn.com/problems/spiral-matrix/\
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<>();
int top = 0, down = matrix.length - 1;
int left = 0, right = matrix[0].length - 1;
while(true) {
for (int i = left; i <= right; i++) {
res.add(matrix[top][i]);
}
top++;
if (top > down) break;
for (int i = top; i <= down; i++) {
res.add(matrix[i][right]);
}
right--;
if (right < left) break;
for (int i = right; i >= left; i--) {
res.add(matrix[down][i]);
}
down--;
if (down < top) break;
for(int i = down; i >= top; i--) {
res.add(matrix[i][left]);
}
left++;
if (left > right ) break;
}
return res;
}
}
199. 二叉树的右视图【中等】
https://leetcode-cn.com/problems/binary-tree-right-side-view/
143. 重排链表【中等】
https://leetcode-cn.com/problems/reorder-list/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public void reorderList(ListNode head) {
if (head == null || head.next == null || head.next.next == null) {
return;
}
//找中点,链表分成两个
ListNode slow = head;
ListNode fast = head;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
}
ListNode newHead = slow.next;
slow.next = null;
//第二个链表倒置
newHead = reverseList(newHead);
//链表节点依次连接
while (newHead != null) {
ListNode temp = newHead.next;
newHead.next = head.next;
head.next = newHead;
head = newHead.next;
newHead = temp;
}
}
private ListNode reverseList(ListNode head) {
if (head == null) {
return null;
}
ListNode tail = head;
head = head.next;
tail.next = null;
while (head != null) {
ListNode temp = head.next;
head.next = tail;
tail = head;
head = temp;
}
return tail;
}
}
704. 二分查找【简单】
https://leetcode-cn.com/problems/binary-search/
class Solution {
public int search(int[] nums, int target) {
if (target > nums[nums.length - 1] || target < nums[0] )
return -1;
int left = 0, right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (nums[mid] > target) {
right = mid - 1;
}else if (nums[mid] < target) {
left = mid + 1;
}else if (nums[mid] == target) {
return mid;
}
}
return -1;
}
}