#463 Sort Integers

    xiaoxiao2025-03-24  13

    题目描述:

    Given an integer array, sort it in ascending order. Use selection sort, bubble sort, insertion sort or any O(n2) algorithm.

    Have you met this question in a real interview?  Yes Example

    Given [3, 2, 1, 4, 5], return [1, 2, 3, 4, 5].

    题目思路:

    O(n^2)代价的sort方法有很多,随便想了一种:对于每一个A[i],从j = i + 1...开始寻找比它更小的数,如果找到了就swap i and j,这样保证i永远是i...A.size() - 1中最小的数。

    Mycode(AC = 50ms):

    class Solution { public: /** * @param A an integer array * @return void */ void sortIntegers(vector<int>& A) { // Write your code here for (int i = 0; i < A.size(); i++) { for (int j = i + 1; j < A.size(); j++) { if (A[i] > A[j]) { int tmp = A[i]; A[i] = A[j]; A[j] = tmp; } } } } };

    转载请注明原文地址: https://ju.6miu.com/read-1297362.html
    最新回复(0)