# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def kthToLast(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: int
"""
initial_head=head
last_head=head
cur_gap=0
while cur_gap<k:
last_head=last_head.next
cur_gap+=1
while last_head != None:
initial_head=initial_head.next
last_head=last_head.next
return initial_head.val
2.先排序,然后通过双指针的办法对两个数组进行迭代
class Solution(object):
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
nums1.sort()
nums2.sort()
i=0
j=0
data=[]
while i<=len(nums1)-1 and j<=len(nums2)-1:
if nums1[i]==nums2[j]:
if len(data)>0 and nums2[j]==data[-1]:
i+=1
j+=1
else:
data.append(nums2[j])
i+=1
j+=1
elif nums1[i]>nums2[j]:
j+=1
else:
i+=1
return data
1.排序
class Solution(object):
def sortedSquares(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
nums.sort(key=lambda x:abs(x))
for i in range(len(nums)):
nums[i]*=nums[i]
return nums
2.双指针
class Solution(object):
def sortedSquares(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
i=0
j=len(nums)-1
data=[0]*len(nums)
ini_idx=-1
while i<=j:
s1=nums[i]**2
s2=nums[j]**2
if s1>=s2:
data[ini_idx]=s1
i+=1
else :
data[ini_idx]=s2
j-=1
ini_idx-=1
return data
class Solution(object):
def maxAscendingSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
max_data=0
cur_max=nums[0]
j=1
while j<=len(nums)-1:
if nums[j]>nums[j-1]:
cur_max+=nums[j]
j+=1
else:
max_data=max(max_data,cur_max)
cur_max=nums[j]
j+=1
max_data=max(max_data,cur_max)
return max_data
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
i=0
for j in nums:
if j!=0:
nums[i]=j
i+=1
for k in range(i,len(nums)):
nums[k]=0
return nums
移除元素
import numpy as np
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
nums.sort(key=lambda x:x==val)
data=np.array(nums)
return sum(data!=val)
import numpy as np
class Solution(object):
def removeElement(self, nums, val):
"""
:type nums: List[int]
:type val: int
:rtype: int
"""
if len(nums)==0:
return 0
j=len(nums)-1
for i in range(len(nums)):
if nums[i]==val:
while j>i and nums[j]==val:
j-=1
nums[i],nums[j]=nums[j],nums[i]
if nums[j]==val:
return j
else:
return j+1