leetcode 78 python

phuonglonglebao

New member
#leetcode #78 #Python #Algorithms #DatScetures ## LeetCode 78: Xoay Array

Cho một mảng, xoay mảng sang phải bằng các bước k.

**Ví dụ 1:**

`` `
Đầu vào: [1,2,3,4,5,6,7], k = 3
Đầu ra: [5,6,7,1,2,3,4]
`` `

** Ví dụ 2: **

`` `
Đầu vào: [-1, -100,3,99], k = 2
Đầu ra: [3,99, -1, -100]
`` `

**Giải pháp:**

`` `Python
def xoay (nums, k):
n = len (nums)
k %= n
# đảo ngược các yếu tố k đầu tiên
nums [: k] = nums [n-k: n] + nums [: n-k]
# đảo ngược phần còn lại của các yếu tố
nums [k:] = nums [n-k: n] + nums [k: n-k]
trả lại num

`` `

** Độ phức tạp về thời gian: ** O (n)

** Độ phức tạp không gian: ** O (1)
=======================================
#leetcode #78 #Python #Algorithms #DataStructures ## Leetcode 78: Rotate Array

Given an array, rotate the array to the right by k steps.

**Example 1:**

```
Input: [1,2,3,4,5,6,7], k = 3
Output: [5,6,7,1,2,3,4]
```

**Example 2:**

```
Input: [-1,-100,3,99], k = 2
Output: [3,99,-1,-100]
```

**Solution:**

```python
def rotate(nums, k):
n = len(nums)
k %= n
# reverse the first k elements
nums[:k] = nums[n-k:n] + nums[:n-k]
# reverse the rest of the elements
nums[k:] = nums[n-k:n] + nums[k:n-k]
return nums

```

**Time Complexity:** O(n)

**Space Complexity:** O(1)
 
Join ToolsKiemTrieuDoGroup
Back
Top
AdBlock Detected

We get it, advertisements are annoying!

Sure, ad-blocking software does a great job at blocking ads, but it also blocks useful features of our website. For the best site experience please disable your AdBlocker.

I've Disabled AdBlock