题目链接:704二分查找
解题思路:
代码
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
left = 0
right = len(nums)
while left < right:
mid = (left + right) / 2
if nums[mid] == target:
return mid
if nums[mid] > target:
right -= 1
if nums[mid] < target:
left += 1
return -1
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
left = 0
right = len(nums) -1
while left <= right:
mid = (left + right) / 2
if nums[mid] == target:
return mid
if nums[mid] > target:
right -= 1
if nums[mid] < target:
left += 1
return -1
题目链接:27去除元素
解题思路:
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
slow = 0
fast = 0
while fast < len(nums):
if nums[fast] != val:
nums[slow] = nums[fast]
slow += 1
fast += 1
return slow
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int slow = 0;
int fast = 0;
while (fast < nums.size()) {
if (nums[fast] != val) {
nums[slow] = nums[fast];
slow++;
}
fast++;
}
return slow;
}
};