Title, in a sequence of already sorted numbers, swapped two elements. For example:
nums[] = {1,2,3,4,5,6,7,8,9,10}
After swapping two elements (for example, exchanging numbers 5 and 9 ):
nums[] = {1,2,3,4,9,6,7,8,5,10}
The question is how do we find these two elements in the array?
Ideas
Assume that the two elements of the interchange are the x and y , and x < y . The other numbers are Ni . Then the problem can be expressed as:
nums[] = {N1 , N2 , N3 , Ni , x , Ni+2 , ... , y , ...,Nm }
Exchange x and y post
nums[] = {N1 , N2 , N3 , Ni , y , Ni+2 , ... , x , ...,Nm }
First Find Y
You can see that it is y Ni+2 larger and must appear first, so we can define a subscript cur . If nums[cur-1] > nums[cur] nums[cur-1] that's the y we're looking for.
and find X.
xis also the condition of nums[cur-1] > nums[cur] nums[cur] x. One thing to note here is that if you do nums[cur-1] > nums[cur] , then the condition of X is satisfied. If that Ni+2 's the x case, it's the right thing to do. If Ni+2 not x , the following must be the condition, x Replace.
Code
intnullnull;for(int1 ; cur < nums.length ; cur++){ ifnull && nums[cur-1] > nums[cur]){ first = nums[cur-1]; } //注意不能用else,否则x,y相邻的情况会无法匹配 ifnull && nums[cur-1] > nums[cur]){ secon = nums[cur]; }}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Swapping two elements in a sorted array