<div class="image-package"><img src="https://img.haomeiwen.com/i1648392/dfd23971784fb2ec.jpg" img-data="{"format":"jpeg","size":327629,"height":900,"width":1600}" class="uploaded-img" style="min-height:200px;min-width:200px;" width="auto" height="auto"/>
</div><h1 id="a3rpr">977. 有序数组的平方</h1><blockquote><p>给你一个按 非递减顺序 排序的整数数组 nums,返回 每个数字的平方 组成的新数组,要求也按 非递减顺序 排序。
示例 1:
输入:nums = [-4,-1,0,3,10]
输出:[0,1,9,16,100]
解释:平方后,数组变为 [16,1,0,9,100]
排序后,数组变为 [0,1,9,16,100]
示例 2:
输入:nums = [-7,-3,2,3,11]
输出:[4,9,9,49,121]
提示:
1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums 已按 非递减顺序 排序
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/squares-of-a-sorted-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。</p><p>
</p></blockquote><h2 id="zuy1y">题解</h2><div class="image-package"><img src="https://img.haomeiwen.com/i1648392/88e91aea0f46e477.jpg" img-data="{"format":"jpeg","size":9895,"height":132,"width":486}" class="uploaded-img" style="min-height:200px;min-width:200px;" width="auto" height="auto"/>
</div><h3 id="cfve3">Swift</h3><blockquote><p>import UIKit
class Solution {
func sortedSquares(_ nums: [Int]) -> [Int] {
guard !nums.isEmpty else {
return []
}
var result = [Int](repeating: 0, count: nums.count)
var left = 0, right = nums.count - 1
var lastIndex = nums.count - 1
while left <= right {
if abs(nums[left]) >= abs(nums[right]) {
result[lastIndex] = nums[left] * nums[left]
left += 1
} else {
result[lastIndex] = nums[right] * nums[right]
right -= 1
}
lastIndex -= 1
}
return result
}
}
print(Solution().sortedSquares([-4, -1, 0, 3, 10]))
</p><p>
</p></blockquote><p>
</p><h1 id="qq01i">189. 轮转数组</h1><blockquote><p>给你一个数组,将数组中的元素向右轮转 k 个位置,其中 k 是非负数。
示例 1:
输入: nums = [1,2,3,4,5,6,7], k = 3
输出: [5,6,7,1,2,3,4]
解释:
向右轮转 1 步: [7,1,2,3,4,5,6]
向右轮转 2 步: [6,7,1,2,3,4,5]
向右轮转 3 步: [5,6,7,1,2,3,4]
示例 2:
输入:nums = [-1,-100,3,99], k = 2
输出:[3,99,-1,-100]
解释:
向右轮转 1 步: [99,-1,-100,3]
向右轮转 2 步: [3,99,-1,-100]
提示:
1 <= nums.length <= 105
-231 <= nums[i] <= 231 - 1
0 <= k <= 105
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/rotate-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。</p></blockquote><h2 id="smy5q">题解</h2><div class="image-package"><img src="https://img.haomeiwen.com/i1648392/19e4fb4aa6911360.jpg" img-data="{"format":"jpeg","size":9100,"height":142,"width":503}" class="uploaded-img" style="min-height:200px;min-width:200px;" width="auto" height="auto"/>
</div><h3 id="fjqck">Swift</h3><blockquote><p>class Solution {
func rotate(_ nums: inout [Int], _ k: Int) {
let tempIndex = k % nums.count
nums.reverse()
nums[0 ..< tempIndex].reverse()
nums[tempIndex ..< nums.count].reverse()
}
}
var nums = [1, 2, 3, 4, 5, 6, 7]
Solution().rotate(&nums, 3)
print(nums)
</p></blockquote><p>
</p><p>
</p><p>
</p><p>
</p>
网友评论