一、知识点介绍
1.数组的定义
2.数组的存储
(1)n维数组的定义
(2)数组存储的特点
(3)常见数组的存储
二、例题题解
1.两数之和
给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
题解一
暴力双循环
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
result=[]
for i in range(len(nums)-1):
for j in range(i+1,len(nums)):
if nums[i]+nums[j]==target:
result.append(i)
result.append(j)
return result
return result
题解二
利用Map的特性,查找是否存在target-val在Map中,以空间换时间
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
record={}
for idx, val in enumerate(nums):
if target-val not in record:
record[val]=idx
else:
return [record[target-val],idx]
2.最接近的三数之和
给你一个长度为 n 的整数数组 nums 和 一个目标值 target。请你从 nums 中选出三个整数,使它们的和与 target 最接近。
返回这三个数的和。
假定每组输入只存在恰好一个解。
题解
单层循环内套双指针法
暴力三循环可能会超时
class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums = sorted(nums)
result=10000
error=10000
for i in range(len(nums)-2):
start=i+1
end=len(nums)-1
while start<end:
tmp=nums[i]+nums[start]+nums[end]
if tmp==target:
return tmp
else:
if abs(tmp-target)<error:
result=tmp
error=abs(tmp-target)
if tmp<target:
start+=1
else:
end-=1
return result
3.移除元素
给你一个数组 nums 和一个值 val,你需要 原地 移除所有数值等于 val 的元素,并返回移除后数组的新长度。
不要使用额外的数组空间,你必须仅使用 O(1) 额外空间并 原地 修改输入数组。
元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。
题解
快慢指针法
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
slow=0
for i in range(len(nums)):
if nums[i]!=val:
nums[slow]=nums[i]
slow+=1
return slow
4.删除有序数组中的重复项
给你一个有序数组 nums ,请你 原地 删除重复出现的元素,使每个元素 只出现一次 ,返回删除后数组的新长度。
不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成。
题解
上一道题稍微修改一下,也是快慢指针法
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
cur=-9999999
slow=0
for fast in range(len(nums)):
if nums[fast]!=cur:
nums[slow]=nums[fast]
slow+=1
cur=nums[fast]
return slow
5.三数之和
给你一个包含 n 个整数的数组 nums,判断 nums 中是否存在三个元素 a,b,c ,使得 a + b + c = 0 ?请你找出所有和为 0 且不重复的三元组。
注意:答案中不可以包含重复的三元组。
题解
先排序再处理,外层循环指定第一个数,内层套双指针。
由于排序的特性,且双指针起始时分别指最小的数和最大的数。
当累加和和目标值有出入时,相应地改变相应指针的位置以接近目标值。
需要处理特殊情况(重复),比如多个相同的数。
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums=sorted(nums)
res=[]
for i in range(len(nums)-2):
if i!=0 and nums[i]==nums[i-1]:
continue
start,end=i+1,len(nums)-1
while start<end:
sum=nums[i]+nums[start]+nums[end]
if sum==0:
res.append([nums[i],nums[start],nums[end]])
while start<end and nums[start]==nums[start+1]:
start+=1
while start<end and nums[end]==nums[end-1]:
end-=1
start+=1
end-=1
elif sum<0:
start+=1
else:
end-=1
return res