leetcode hot topic 2
Given a non -empty array. Except for only one element, each element appears twice. Find the element that only appears once.
Your algorithm should have a linear time complexity. Can you achieve it without extra space?
class Solution: def singleNumber(self, nums: List[int]) -> int: a=0 for i in nums: a=a^i return a
Given an array of n, and find most of them. Most elements refer to elements that appear in the array greater than ⌊ n/2 ⌋.
You can assume that the array is non -empty, and the given array always has a majority element.
class Solution: def majorityElement(self, nums: List[int]) -> int: count=1 maj=nums for i in range(1,len(nums)): if maj==nums[i]: count+=1 else: count-=1 if count==0: maj=nums[i+1] return maj
merge the two linked linked lists into a new linked list and return. The new linked list is composed of all nodes of the two linked list given by stitching.
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: if l1==None: return l2 if l2==None: return l1 res=l1 if l1.val<l2.val else l2 res.next=self.mergeTwoLists(res.next,l2 if l1.val<l2.val else l1) return res
Given a array Nums, write a function to move all 0 to the end of the array, while maintaining the relative order of non -zero elements.
class Solution: def moveZeroes(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ nums.sort(key=bool,reverse=True)
Given a integer array with a range of 1 ≤ a [i] ≤ n (n = array size). Some of the elements in the array appear twice, and others only appear once.
Find the number that does not appear in the array between the [1, n] range.
Can you complete this task without using extra space and time complexity of time O (n)? You can assume that the returned array is not counted in additional space.
class Solution: def findDisappearedNumbers(self, nums: List[int]) -> List[int]: a=set([i for i in range(1,len(nums)+1)]) nums=set(nums) return a-nums