mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
Merge pull request #273 from Simonhancrew/master
添加 0977.有序数组的平方 Python3 Go Rust版本
This commit is contained in:
@ -100,10 +100,66 @@ public:
|
|||||||
Java:
|
Java:
|
||||||
|
|
||||||
Python:
|
Python:
|
||||||
|
```Python
|
||||||
|
class Solution:
|
||||||
|
def sortedSquares(self, nums: List[int]) -> List[int]:
|
||||||
|
n = len(nums)
|
||||||
|
i,j,k = 0,n - 1,n - 1
|
||||||
|
ans = [-1] * n
|
||||||
|
while i <= j:
|
||||||
|
lm = nums[i] ** 2
|
||||||
|
rm = nums[j] ** 2
|
||||||
|
if lm > rm:
|
||||||
|
ans[k] = lm
|
||||||
|
i += 1
|
||||||
|
else:
|
||||||
|
ans[k] = rm
|
||||||
|
j -= 1
|
||||||
|
k -= 1
|
||||||
|
return ans
|
||||||
|
```
|
||||||
|
|
||||||
Go:
|
Go:
|
||||||
|
```Go
|
||||||
|
func sortedSquares(nums []int) []int {
|
||||||
|
n := len(nums)
|
||||||
|
i, j, k := 0, n-1, n-1
|
||||||
|
ans := make([]int, n)
|
||||||
|
for i <= j {
|
||||||
|
lm, rm := nums[i]*nums[i], nums[j]*nums[j]
|
||||||
|
if lm > rm {
|
||||||
|
ans[k] = lm
|
||||||
|
i++
|
||||||
|
} else {
|
||||||
|
ans[k] = rm
|
||||||
|
j--
|
||||||
|
}
|
||||||
|
k--
|
||||||
|
}
|
||||||
|
return ans
|
||||||
|
}
|
||||||
|
```
|
||||||
|
Rust
|
||||||
|
```
|
||||||
|
impl Solution {
|
||||||
|
pub fn sorted_squares(nums: Vec<i32>) -> Vec<i32> {
|
||||||
|
let n = nums.len();
|
||||||
|
let (mut i,mut j,mut k) = (0,n - 1,n- 1);
|
||||||
|
let mut ans = vec![0;n];
|
||||||
|
while i <= j{
|
||||||
|
if nums[i] * nums[i] < nums[j] * nums[j] {
|
||||||
|
ans[k] = nums[j] * nums[j];
|
||||||
|
j -= 1;
|
||||||
|
}else{
|
||||||
|
ans[k] = nums[i] * nums[i];
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
k -= 1;
|
||||||
|
}
|
||||||
|
ans
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||||
|
Reference in New Issue
Block a user