We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
- Prepare
- Algorithms
- Implementation
- Larry's Array
- Discussions
Larry's Array
Larry's Array
Sort by
recency
|
356 Discussions
|
Please Login in order to post a comment
I use a quite intuitive approach to construct solution in Python. To sort a list using swapping among 3 numbers, one may begin with the smallest number, and moving it forward to the beginning of the list every time by 2 numbers. For example: [5,4,3,2,1] --> [5,4,1,3,2] --> [1,5,4,3,2]. In this case by this iteration alone can bring the smallest number to the front. But in cases like [4,3,2,1], it will become [4,1,3,2], the last swapping moving the first number to third position, ie [1,3,4,2]. By popping out the smallest number(1), we can repeat the procedure to the second smallest(2). At the end there will be two numbers remaining, if first one is smaller than the second, the whole list is sortable, otherwise no.
So the following code is constructed:
The code works but fails about half of the tests due to time limit issue. A review concludes that the repeated reconstructions of the list by moving the smallest number forward 2 positions is unnecessary. At the end either the smallest number, if its index is even, can be moved to position 0 without disturbing other numbers, or it can be moved to position 1 and swap the position 0 number to position 2. The following rewritten code successfully passes all the tests:
Using Python :
def larrysArray(A): # Write your code here c=0 for i in range(0,len(A)-1): for j in range(i,len(A)): if(A[i]>A[j]): c+=1 if(c%2==0): return "YES" else: return "NO"
my answer in Typescript
string larrysArray(vector A) { int counter =0; for(int i=0;iA[j]){ counter++; } } } return (counter%2==0) ? "YES" : "NO"; } jinx manga
string larrysArray(vector A) { int counter =0; for(int i=0;iA[j]){ counter++; } } } return (counter%2==0) ? "YES" : "NO"; }