Leetcode Part 1

Oct 24, 2018

https://leetcode.com/explore/featured/card/top-interview-questions-easy/92/array/646/

Array

Rotate Array

刚开始没仔细看题,就写了个 nums[-k:] + nums[:k],后来发现题目中要求 do it in-place,并且要兼容各种 cases,最终写成

nums[:] = (nums[:-k][::-1] + nums[-k:][::-1])[::-1]

25 / 34 test cases passed.

卡在了 nums = [1,2]; k = 3,于是加上

k = k % len(nums)

终于 accepted 了

Strings

Reverse String

用 Python 写简单

s[::-1]

Reverse Integer

x = str(x)
y = -int(x.replace('-', '')[::-1]) if '-' in x else int(x[::-1])
return y if -1 << 31 <= y and y <= (1 << 31) - 1 else 0

这里用 2**31 或者 (1 << 31) - 1 都行

Best practise:

def reverse(self, x):
  s = cmp(x, 0)
  r = int(`s*x`[::-1])
  return s*r * (r < 2**31)

[back]