【Leetcode】【python】Array Partition I, Number Complement
来源:互联网 发布:玩具出租软件 编辑:程序博客网 时间:2024/06/06 01:26
Array Partition I
题目大意
给定一个长度为2n的整数数组,将数组分成n组,求每组数的最小值之和的最大值
解题思路
偶数数组,排序后奇数位置所有相加就可以
代码
class Solution(object): def arrayPairSum(self, nums): """ :type nums: List[int] :rtype: int """ return sum(sorted(nums)[::2])
我提交的
class Solution(object): def arrayPairSum(self, nums): """ :type nums: List[int] :rtype: int """ nums.sort() # print nums total = 0 for i in range(0, len(nums), 2): total += nums[i] return total
总结
可以看到答案使用了sorted()以及切片,值得学习。尤其是切片,我平常不怎么用。
Number Complement
题目大意
给定一个正整数,输出其补数。
解题思路
二进制位取反
代码
class Solution(object): def findComplement(self, num): i = 1 while i <= num: i = i << 1 return (i - 1) ^ num
我提交的
class Solution(object): def findComplement(self, num): """ :type num: int :rtype: int """ list_num = [] list_num = list(str(bin(num))) # print list_num for i in range(len(list_num)-2): if list_num[i+2] == '1': list_num[i+2] = '0' else: list_num[i+2] = '1' # print list_num num_str = ''.join(list_num) return int(num_str,2)
总结
我提交的
- 思路是int-bin-list-按位数1、0转换,最后list-str-int
- int(num_str,2),是将字符串以二进制转为整数
- num_str = ”.join(list_num) 将list转为拼接后的str。
代码
左移位,i从1开始,到2、4、8,假设输入还是5,那么到8之后,减1,得到7。
7^num: 111^101=010=2
简单来说就是用1,111,1111,11111去和实际num的二进制做异或运算,这样就能取到反。
一来说明python取反的~并不能解决这道题目,而来说明压根没好好想啊
阅读全文
0 0
- 【Leetcode】【python】Array Partition I, Number Complement
- [LeetCode]Number Complement - Python
- [leetcode: Python]561. Array Partition I
- LeetCode Array Partition I
- leetCode---Array Partition I
- Array Partition I(leetcode)
- Leetcode-Array Partition I
- leetcode Array Partition I
- [leetcode: Python]476. Number Complement
- LeetCode 561. Array Partition I
- LeetCode 561. Array Partition I
- [LeetCode]561. Array Partition I
- leetcode#561 Array Partition I
- leetcode 561. Array Partition I
- LeetCode 561. Array Partition I
- Leetcode 561. Array Partition I
- leetcode-561-Array Partition I
- Leetcode 561: Array Partition I
- 链表-leetcode 138. Copy List with Random Pointer
- An entity object cannot be referenced by multiple instances of IEntityChangeTracker错误解决
- 通向架构师的道路(第七天)之漫谈使用ThreadLocal改进你的层次的划分
- VBA插入行和插入列的作用域
- 树莓派安装centos7乱码解决
- 【Leetcode】【python】Array Partition I, Number Complement
- 【JavaScript转义字符对照表】
- 欢迎使用CSDN-markdown编辑器
- CenOS7搭建Redis-3.2.9及整合Jedis
- 一篇文章梳理完 AR 背后的八大关键性技术
- 通向架构师的道路(第八天)之weblogic与apache的整合与调优
- CentOS 7 firewalld vsftpd开放端口
- 通向架构师的道路(第九天)之weblogic的集群与配置
- 六月总结~