面试常见算法题

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("hello world");
    }

}
hello world
//快排 以左基准数拿出跳跃插空
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;

void msort(int a[], int l, int r)
{
    if (l >= r) return;
    int key = a[l];
    int low = l, high = r;
    while (low < high)
    {
        while (low < high && a[high] > key) high--;
        a[low] = a[high];
        while (low < high && a[low] < key) low++;
        a[high] = a[low];
    }
    a[low] = key;
    msort(a, l, low - 1);
    msort(a, low + 1, r);
}

int a[100005];
int main()
{
    int n;
    scanf("%d", &n);
    for (int i = 1; i <= n; i++)
        scanf("%d", &a[i]);
    msort(a, 1, n);
    for (int i = 1; i <= n; i++)
        printf("%d ", a[i]);
    printf("\n");
}
快排
/**
 * 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) {
        if (head == null) return head;
        ListNode p1 = head;
        ListNode p2 = head.next;
        while (p2 != null) {
            ListNode p3 = p2.next;
            p2.next = p1;
            p1 = p2;
            p2 = p3;
        }
        head.next = null;
        return p1;
    }
}
反转链表
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        preorder(root, res);
        return res;
    }

    public void preorder(TreeNode root, List<Integer> res) {
        if (root == null) {
            return;
        }
        res.add(root.val);
        preorder(root.left, res);
        preorder(root.right, res);
    }
}


/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Deque<TreeNode> stack = new LinkedList<>();
        while(root != null || !stack.isEmpty()) {
            while(root != null) {
                res.add(root.val);
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            root = root.right;
        }
        return res;
    }
}
前序遍历
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        Deque<TreeNode> stk = new LinkedList<TreeNode>();
        while (root != null || !stk.isEmpty()) {
            while (root != null) {
                stk.push(root);
                root = root.left;
            }
            root = stk.pop();
            res.add(root.val);
            root = root.right;
        }
        return res;
    }
}
中序遍历
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        LinkedList<Integer> result = new LinkedList<>();
        Stack<TreeNode> stack = new Stack<>();
        while (root != null || !stack.isEmpty()) {
            if (root != null) {
                stack.push(root);
                result.addFirst(root.val);
                root = root.right;
            } else {
                root = stack.pop();
                root = root.left;
            }
        }

        return result;
    }
}
后序遍历
public class Node {
    Node(int key, int value) {
        this.key = key;
        this.value = value;
    }
    public Node pre;
    public Node next;
    public int key;
    public int value;
}

class LRUCache {
    private Node head;
    private Node tail;
    private int limit;
    private HashMap<Integer, Node> hashMap = new HashMap<>();

    public LRUCache(int capacity) {
        this.limit = capacity;
    }

    private int removeNode(Node node) {
        if (node == tail && node == head) {
            head = null;
            tail = null;
        } else if (node == tail) tail = node.pre;
        else if (node == head) head = node.next;
        else {
            node.pre.next = node.next;
            node.next.pre = node.pre;
        }
        return node.key;
    }

    private void addNode(Node node) {
        if (head == null) head = node;
        if (tail != null) {
            tail.next = node;
            node.pre = tail;
            node.next = null;
        }
        tail = node;
    }

    private void refreshNode(Node node) {
        if (node == tail) return;
        removeNode(node);
        addNode(node);
    }

    public int get(int key) {
        Node node = hashMap.get(key);
        if (node == null) return -1;
        refreshNode(node);
        return node.value;
    }

    public void put(int key, int value) {
        Node node = hashMap.get(key);
        if (node == null) {
            if (hashMap.size() >= limit) {
                int old = removeNode(head);
                hashMap.remove(old);
            }
            node = new Node(key, value);
            addNode(node);
            hashMap.put(key, node);
        } else {
            node.value = value;
            refreshNode(node);
        }
    }

}

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache obj = new LRUCache(capacity);
 * int param_1 = obj.get(key);
 * obj.put(key,value);
 */
LRU
class Solution {
    public int findKthLargest(int[] nums, int k) {
        return quickSort(nums, k, 0, nums.length - 1);
    }

    private int quickSort(int[] nums,int k,int left,int right){
        int index = (left + right) / 2;
        int flag=nums[index];
        nums[index]=nums[left];
        int i=left,j=right;
        while (i<j){
            while (i<j&&nums[j]<=flag) j--;
            nums[i]=nums[j];
            while (i<j&&nums[i]>=flag) i++;
            nums[j]=nums[i];
        }
        nums[i]=flag;
        if (i==k-1) return nums[i];
        else if (i<k-1) return quickSort(nums,k,i+1,right);
        else return quickSort(nums,k,left,i-1);
    }
}
数组第k大
class MyCircularQueue {

    private int[] queue;
    private int headIndex;
    private int count;
    private int capacity;

    /** Initialize your data structure here. Set the size of the queue to be k. */
    public MyCircularQueue(int k) {
        this.capacity = k;
        this.queue = new int[k];
        this.headIndex = 0;
        this.count = 0;
    }

    /** Insert an element into the circular queue. Return true if the operation is successful. */
    public boolean enQueue(int value) {
        if (this.count == this.capacity)
        return false;
        this.queue[(this.headIndex + this.count) % this.capacity] = value;
        this.count += 1;
        return true;
    }

    /** Delete an element from the circular queue. Return true if the operation is successful. */
    public boolean deQueue() {
        if (this.count == 0)
        return false;
        this.headIndex = (this.headIndex + 1) % this.capacity;
        this.count -= 1;
        return true;
    }

    /** Get the front item from the queue. */
    public int Front() {
        if (this.count == 0)
        return -1;
        return this.queue[this.headIndex];
    }

    /** Get the last item from the queue. */
    public int Rear() {
        if (this.count == 0)
        return -1;
        int tailIndex = (this.headIndex + this.count - 1) % this.capacity;
        return this.queue[tailIndex];
    }

    /** Checks whether the circular queue is empty or not. */
    public boolean isEmpty() {
        return (this.count == 0);
    }

    /** Checks whether the circular queue is full or not. */
    public boolean isFull() {
        return (this.count == this.capacity);
    }
}

/**
 * Your MyCircularQueue object will be instantiated and called as such:
 * MyCircularQueue obj = new MyCircularQueue(k);
 * boolean param_1 = obj.enQueue(value);
 * boolean param_2 = obj.deQueue();
 * int param_3 = obj.Front();
 * int param_4 = obj.Rear();
 * boolean param_5 = obj.isEmpty();
 * boolean param_6 = obj.isFull();
 */
循环队列
/**
 * 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 addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode ans = new ListNode();
        ListNode pre = ans;
        int last = 0;

        while (l1 != null || l2 != null) {
            int num = last;
            if (l1 != null) {
                num += l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                num += l2.val;
                l2 = l2.next;
            }
            ListNode next = new ListNode(num % 10);
            pre.next = next;
            last = num / 10;
            pre = next;
        }

        if (last != 0) {
            ListNode next = new ListNode(last);
            pre.next = next;
        } 

        return ans.next;
    }
}
大数相加
class Solution {
    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        double ans = 0.0;
        int nums = nums1.length + nums2.length;
        if (nums % 2 == 1) {
            ans = 1.0 * findKth(nums1, nums2, nums / 2 + 1);
        } else {
            ans = 1.0 * (findKth(nums1, nums2, nums / 2) + findKth(nums1, nums2, nums / 2 + 1)) / 2;
        }
        return ans;
    }

    private int findKth(int[] nums1, int[] nums2, int k) {
        int len1 = nums1.length;
        int len2 = nums2.length;

        int s1 = 0, s2 = 0;

        while (true) {
            if (s1 == len1) return nums2[s2 + k - 1];
            if (s2 == len2) return nums1[s1 + k - 1];
            if (k == 1) {
                return Math.min(nums1[s1], nums2[s2]);
            }

            int half = k / 2;
            int ns1 = Math.min(s1 + half, len1) - 1;
            int ns2 = Math.min(s2 + half, len2) - 1;
            if (nums1[ns1] <= nums2[ns2]) {
                k -= (ns1 - s1 + 1);
                s1 = ns1 + 1;
            } else {
                k -= (ns2 - s2 + 1);
                s2 = ns2 + 1;
            }
        }
    }
}
两个升序数组第k大
#include<stdio.h>
#include<string.h>
#include<time.h>
#include<algorithm>
using namespace std;

int n = 50000;

void select(int b[])
{
    for (int i = 1; i <n; i++)
        for (int j = i + 1; j <= n; j++)
            if (b[i] > b[j]) swap(b[i], b[j]);
}

void bubble(int b[])
{
    for (int i = 1; i < n; i ++)
        for (int j = 1; j < n; j ++)
            if (b[j] > b[j + 1]) swap(b[j], b[j + 1]);
}

void quick(int b[], int l, int r)
{
    int i = l, j = r, x, y;
    x = b[(l + r) / 2];
    while (i <= j)
    {
        while (b[i] < x) i++;
        while (x < b[j]) j--;
        if (i <= j)
        {
            swap(b[i], b[j]);
            i++; j--;
        }
    }
    if (i < r) quick(b, i, r);
    if (l < j) quick(b, l, j);
}

int c[1000005];
void merge(int b[], int l, int r, int mid)
{
    for (int i = l; i <= r; i++) c[i] = b[i];
    int x1 = l, x2 = mid + 1;
    for (int i = l; i <= r; i++)
    {
        if (x1 > mid) b[i] = c[x2++];
        else if (x2 > r) b[i] = c[x1++];
        else if (c[x1] < c[x2]) b[i] = c[x1++];
        else b[i] = c[x2++];
    }
}
void mergesort(int b[], int l, int r)
{
    int mid = (l + r) / 2;
    if (l >= r) return;
    mergesort(b, l, mid);
    mergesort(b, mid + 1, r);
    merge(b, l, r, mid);
}

void insert(int b[])
{
    for (int i = 2; i <= n; i++)
    {
        int j = i;
        while (j > 1 && b[j] < b[j - 1])
        {
            swap(b[j], b[j - 1]);
            j--;
        }
    }
}

void heap(int b[], int i, int size)
{
    int child;
    for (; 2 * i <= size; i = child)
    {
        child = 2 * i;
        if (child < size && b[child + 1] > b[child]) child++;
        if (b[i] < b[child]) swap(b[i], b[child]);
        else break;
    }
}
void heapsort(int b[])
{
    for (int i = n / 2; i >= 1; i--)
        heap(b, i, n);
    for (int i = n; i > 1; i--)
    {
        swap(b[i], b[1]);
        heap(b, 1, i - 1);
    }
}

int a[1000005], b[1000005];
int main()
{
    srand(time(0));
    for (int i = 1; i <= n; i++) a[i] = rand();
    clock_t begin, duration;

    for (int i = 1; i <= n; i++) b[i] = a[i];
    begin = clock();
    select(b);
    duration = clock() - begin;
//    for (int i = 1; i <= n; i++) printf("%d ",b[i]); printf("\n");
    printf("select sort = %dms\n\n",duration*1000/CLOCKS_PER_SEC);

    for (int i = 1; i <= n; i++) b[i] = a[i];
    begin = clock();
    bubble(b);
    duration = clock() - begin;
//    for (int i = 1; i <= n; i++) printf("%d ",b[i]); printf("\n");
    printf("bubble sort = %dms\n\n",duration*1000/CLOCKS_PER_SEC);

    for (int i = 1; i <= n; i++) b[i] = a[i];
    begin = clock();
    quick(b, 1, n);
    duration = clock() - begin;
//    for (int i = 1; i <= n; i++) printf("%d ",b[i]); printf("\n");
    printf("quick sort = %dms\n\n",duration*1000/CLOCKS_PER_SEC);

    for (int i = 1; i <= n; i++) b[i] = a[i];
    begin = clock();
    mergesort(b, 1, n);
    duration = clock() - begin;
//    for (int i = 1; i <= n; i++) printf("%d ",b[i]); printf("\n");
    printf("merge sort = %dms\n\n",duration*1000/CLOCKS_PER_SEC);

    for (int i = 1; i <= n; i++) b[i] = a[i];
    begin = clock();
    insert(b);
    duration = clock() - begin;
//    for (int i = 1; i <= n; i++) printf("%d ",b[i]); printf("\n");
    printf("insert sort = %dms\n\n",duration*1000/CLOCKS_PER_SEC);

    for (int i = 1; i <= n; i++) b[i] = a[i];
    begin = clock();
    heapsort(b);
    duration = clock() - begin;
//    for (int i = 1; i <= n; i++) printf("%d ",b[i]); printf("\n");
    printf("heap sort = %dms\n\n",duration*1000/CLOCKS_PER_SEC);
}
几种排序时间的比较

 

posted on 2022-02-03 20:26  xiao_xin  阅读(83)  评论(0)    收藏  举报

导航