You are given two sorted arrays that contain only integers. Your task is to find a way to merge them into a single one, sorted inascending order. Complete the function
mergeArrays(arr1, arr2)
, wherearr1
andarr2
are the original sorted arrays.You don't need to worry about validation, since
arr1
andarr2
must be arrays with 0 or more Integers. If botharr1
andarr2
are empty, then just return an empty array.Note:
arr1
andarr2
may be sorted in different orders. Alsoarr1
andarr2
may have same integers. Remove duplicated in the returned result.Examples
arr1 = [1, 2, 3, 4, 5]; arr2 = [6, 7, 8, 9, 10]; mergeArrays(arr1, arr2); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] arr3 = [1, 3, 5, 7, 9]; arr4 = [10, 8, 6, 4, 2]; mergeArrays(arr3, arr4); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] arr5 = [1, 3, 5, 7, 9, 11, 12]; arr6 = [1, 2, 3, 4, 5, 10, 12]; mergeArrays(arr5, arr6); // [1, 2, 3, 4, 5, 7, 9, 10, 11, 12]
这个问题可以用list.extend()连接两个list,然后去重,最后list.sort();不过python本身有内建函数set()。在python中,set是基本的数据类型,包含可变集合set(),和不可变集合frozenset()两种。set()集合是无序(所以不能用切片)且不重复的。
创建一个集合
>>> set('boy')
set(['y', 'b', 'o'])
>>> set('boyboyboy')
set(['y', 'b', 'o'])
添加元素,add-整体添加,update-拆分添加,效果上有区别
>>> s=set('girl')
>>> s
set(['i', 'r', 'l', 'g'])
>>> s.add('boy')
>>> s
set(['i', 'boy', 'r', 'l', 'g'])
>>> s.update('man')
>>> s
set(['a', 'boy', 'g', 'i', 'm', 'l', 'n', 'r'])
删除元素
>>> s=set('boy')
>>> s
set(['y', 'b', 'o'])
>>> s.remove('o')
>>> s
set(['y', 'b'])
集合的操作符号
数学符号 | python操作符 | 含义 |
- | - | 差集,相对补集 |
∩ | & | 交集 |
∪ | | | 并集 |
∈ | in | 是成员关系 |
∉ | not in | 不是成员关系 |
等于 | == | 等于 |
不等于 | != | 不等于 |
所以按照集合的思想,本文开头的问题可以这样解决
def func(arr1,arr2):
return sorted(set(arr1)|set(arr2))
或者直接按照集合的互异性,set()函数本身返回的便是一个集合,因此本身就有去重的功能,可以
def func(arr1,arr2):
return sorted(set(arr1+arr2))