26. Remove Duplicates from Sorted Array
Description
Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Example 1
Given nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn't matter what you leave beyond the returned length.
Example 2
Given nums = [0,0,1,1,1,2,2,3,3,4],
Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.
It doesn't matter what values are set beyond the returned length.
思路及代码
这里借鉴到的是插入排序的思想,因为输入为有序数组,所以我这里将数组分为两个区间,一个区间为已筛选区间,一个区间为未筛选区间,用到两个指针,其中一个指针j指向已筛选区间的最后一个元素,另一个指针用于遍历数组,当遇到下一个不重复的元素时,j指针才会向后移动,详细的方式可以看上面的图。对应的Python代码如下:
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
p = 0
for i in range(n):
if (nums[i] != nums[p]):
p = p + 1
nums[p], nums[i] = nums[i], nums[p]
del nums[p + 1: ]
return p + 1
69. Sqrt(x)
Description
Implement int sqrt (int x).
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
Example 1
Input: 4
Output: 2
Example 2
Input: 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since
the decimal part is truncated, 2 is returned.
思路及代码
这里用二分查找的方法,题目要求给出的答案向下取整,那么当我们找到的值mid的平方小于x而mid + 1的值大于x时,mid即为我们要找的答案。对应的Python代码如下:
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
if x < 1:
return 0
low = 1
high = x
while low <= high:
mid = (high + low) // 2
if (mid ** 2 > x):
high = mid - 1
elif (mid ** 2 == x):
return mid
else:
if (mid ** 2 < x) and ((mid + 1) ** 2 > x):
return mid
else:
low = mid + 1