恢复交换两个元素的排序数组

有一个已排序的数组,但是其中有两个元素被交换了位置,你的任务就是恢复它们,使数组重新有序。

例如 输入nums=[1,2,4,3,5,6],输出应该为【1,2,3,4,5,6】。

public class RecoverSortedArray {
    public int[] recover(int[] nums) {
        if(nums == null || nums.length == 1) {
            return nums;
        }
        int first = -1;
        int second = -1;
        for(int i = 0; i < nums.length - 1; ++i) {
            if(nums[i] >= nums[i + 1]) {
                if(first == -1) {
                    first = i;
                    second = i + 1;
                } else {
                    second = i + 1;
                }
            }
        }
        int num = nums[first];
        nums[first] = nums[second];
        nums[second] = num;

        return nums;
    }

    public static void main(String[] args) {
        int[] nums = {6,2,3,4,5,1};
        RecoverSortedArray rsa = new RecoverSortedArray();
        System.out.println(Arrays.toString(rsa.recover(nums)));
    }
}

猜你喜欢

转载自blog.csdn.net/qq_22158743/article/details/88183055