767. Reverse Array
Reverse the given array nums inplace.
Inplace means you can’t use extra space.
Have you met this question in a real interview?
Example
Example 1:
Input : nums = [1,2,5]
Output : [5,2,1]
解题思路:
双指针法 i, j, 分别从头尾向中间遍历,i < j 时交换数值。
不占用额外空间的交换:
a=a+b;
b=a-b;
a=a-b;
class Solution:
"""
@param nums: a integer array
@return: nothing
"""
def reverseArray(self, nums):
# write your code here
i, j = 0, len(nums) - 1
while i < j:
nums[i] = nums[i] + nums[j]
nums[j] = nums[i] - nums[j]
nums[i] = nums[i] - nums[j]
i += 1
j -= 1
return nums
请多多指教。
文章标题:767. Reverse Array
本文作者:顺强
发布时间:2020-04-30, 23:59:00
原始链接:http://shunqiang.ml/leetcode-767-reverse-array/版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。