[Two pointers-facing double pointers] Lintcode 39. Restore rotating sorted array

Lintcode 39. Restore rotated sorted array

Title description: Given a rotating sorted array, restore its sorting in place. (Ascending order) This
Insert picture description here
question is not well understood, and it needs to be implemented in depth later.

class Solution {
    
    
public:
    /**
     * @param nums: An integer array
     * @return: nothing
     */
    void recoverRotatedSortedArray(vector<int> &nums) {
    
    
        int offset = 0;
        for (int i = 1; i < nums.size(); ++i) {
    
    //寻找偏移量
            if (nums[i-1] > nums[i]) {
    
    
                offset = i;   
            }
        }
        if (0 == offset) {
    
    
            return;
        }
        offset = nums.size() - offset;
        
        int gcd = getGCD(offset, nums.size());
        for (int i = 0; i < gcd; ++i) {
    
    
            int next = (i + offset) % nums.size();
            //将每个数放到它们应该放的位置
            while (next != i) {
    
    
                int tmp = nums[i];
                nums[i] = nums[next];
                nums[next] = tmp;
                next = (next + offset) % nums.size();
            }
        }
    }
    
    //辗转相除法求最大公约数
    int getGCD(int a, int b) {
    
    
        if (0 == a % b) {
    
    
            return b;
        }
        return getGCD(b, a % b);
    }
};

Guess you like

Origin blog.csdn.net/phdongou/article/details/113838231
Recommended