【刷题】微软高频题总结

  1. 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.

  1. 迭代法:这个题目要注意,可以在链表前面加一个空节点,这样就可以一次性遍历整个链表。
/**
 * 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;
    }
}
  1. 递归法
    递归法示例
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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值