- Kth Largest Element in an Array
Given an integer array nums and an integer k, return the kth largest element in the array.
Note that it is the kth largest element in the sorted order, not the kth distinct element.
本题主要考察排序方法。这里给出两种排序。
// 冒泡排序
class Solution {
public int findKthLargest(int[] nums, int k) {
int n = nums.length;
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
if(nums[j] < nums[i]){
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
}
}
return nums[n-k];
}
}
快速排序核心思路:
① 若数组只有一个元素,排序结束,直接返回!!! 若数组元素大于一个,随机选择找到一个值pivot,我一般选择数组的最后一个值。
② 将数组中比他小的都移到他的左边,数组中比他大的都移动到他的右边,注意,此时pivot元素就是数组中第(nums.length-position)大的元素,position就是其下标。
③ 将数组以pivot为界分为左右两个小数组,分别转①!!!
快速选择核心思路:
① 将(position和k)作为r指针和l指针变化的标准,来进行二分查找!!!
② 若(position + k == nums.length),找到第k大值,直接返回
③ 若(position + k < nums.length), l指针右移, l = position + 1;
③ 若(position + k > nums.length), r指针左移, r = position ;
// 快速排序
206. Reverse Linked List
Given the head of a singly linked list, reverse the list, and return the reversed 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 ListNode reverseList(ListNode head) {
ListNode node1 = null, node2 = head;
while(node2 != null){
ListNode tmpNode = node2.next;
node2.next = node1;
node1 = node2;
node2 = tmpNode;
}
return node1;
}
}
- 递归法
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode newHead = reverseList(head.next);
head.next.next = head;
head.next = null;
return newHead;
}
}