LeetCode Python 位操作 1
Python 位操作:
按位与 &, 按位或 |
体会不到
按位异或 ^
num ^ num = 0
左移 <<
num << 1 == num * 2**1
右移 >>
num >> 2 == num / 2**2
取反 ~
~num == -(num + 1)
1. Single Number
Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
关键点在于相同整数按位异或为0, 整数与0异或不变, 一个 reduce 搞定. LeetCode 执行效率击败 18.9%.
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return reduce(lambda x,y: x^y, nums)
2. Single Number II
Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
下三路的解法, 如果看到这个答案, 就应该问一下 sum 和 set 的时间空间复杂度各是多少, 为什么. LeetCode: 72.45%.
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return (sum(set(nums)) * 3 - sum(nums)) / 2
3. Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).
Follow up:
If this function is called many times, how would you optimize it?
首先, Python 没有原生对于 unsigned integer 的支持, 其次, 这个是同样下三路的解法. LeetCode: 85.2%.
class Solution:
# @param n, an integer
# @return an integer
def reverseBits(self, n):
string = bin(n)
if n >= 0:
string = string[:2] + string[2:].zfill(32)[::-1]
else:
string = string[:3] + string[3:].zfill(32)[::-1] return int(string, 2)
4. Number of 1 Bits
Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011
, so the function should return 3.
这样刷题一点意思都没有, count 的时间空间复杂度是多少. LeetCode: 62.81%.
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
string = bin(n)
return string.count("")
5. Bitwise AND of Numbers Range
Given a range [m, n] where 0 <= m <= n <= 2147483647, return the bitwise AND of all numbers in this range, inclusive.
For example, given the range [5, 7], you should return 4.
如果用 range, 会报内存不足, 用 xrange 会报超时. 我自己把 [0, 2147483647] 带入, 确实跑不动.
class Solution(object):
def rangeBitwiseAnd(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
return reduce(lambda x,y: x&y, xrange(m, n+1))
观察一下, 其实它的关键是, log(n, 2) 比 log(m, 2) 大多少, 如果大于 1, 那么肯定就是0, 如果小于 1, 就再进行 reduce. LeetCode: 2.52%.
class Solution(object):
def rangeBitwiseAnd(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
if m == 0:
return 0 from math import log
logm = log(m, 2)
logn = log(n, 2) if logn - logm >= 1:
return 0 return reduce(lambda x,y: x&y, xrange(m, n+1))
而使用 log 是明显的作弊, 再顺着刚才的思路, 之前都是从 m 开始考虑, 现在从 n 开始考虑, 因为 & 操作会使 n 迅速下降, 两种情况, 一种是遍历 [m, n] 的 &, 另一种半路上就有0出来了. 并且, 我相信耗时的大户应该是 xrange, 位操作本身应该很快. LeetCode: 70.18%.
class Solution(object):
def rangeBitwiseAnd(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
while m < n:
n &= n - 1 return n
增加 if n == 0 判断, 如果是 0 就 break, 看看能提升多少. LeetCode: 73.09%.
class Solution(object):
def rangeBitwiseAnd(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
while m < n:
n &= n - 1
if n == 0:
break return n
6. Power of Two
Given an integer, write a function to determine if it is a power of two.
首先, 2的0次方为 1, 因此 n >= 1, 然后, 就是对 n 执行 >>= i, 如果 n 是 2 的幂, 那么 n >> i << i == n, 注意我们的目标是计算 i 让 n >> i == 2, 所以 i - 1. LeetCode: 45.27%.
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
if n < 1:
return False i, m = 0, n
while m:
m >>= 1
i += 1 return n >> (i - 1) << (i - 1) == n
260. Single Number III
Given an array of numbers nums
, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.
For example:
Given nums = [1, 2, 1, 3, 2, 5]
, return [3, 5]
.
Note:
- The order of the result is not important. So in the above example,
[5, 3]
is also correct. - Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
首先是下三路的解法, 必然会超时
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
results = []
for i in set(nums):
if nums.count(i) == 1:
results.append(i) if len(results) == 2:
return results
应该还是在考察位操作, 相同的数变成 0 而不同相同的数留下来. 如果全局异或, 最终的值是两个数字的异或. 这个涉及到位操作的细节, 凑不出来了.
我不准备用位操作解这个问题, collections 这个神库里面有个 Counter 类, 参数是 iterable 的对象, 对对象中的 hashable 对象进行计数.
sorted 可以对字典的 values 进行排序. LeetCode: 45.7%.
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
from collections import Counter
counter = Counter(nums)
return [_[0] for _ in sorted(counter.items(), key=lambda x: x[1])[:2]]
268. Missing Number
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n
, find the one that is missing from the array.
For example,
Given nums = [0, 1, 3]
return 2
.
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
等差数列之和, LeetCode: 78.18%.
class Solution(object):
def missingNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
length = len(nums)
gauss_sum = length * (length - 1) / 2 + length
nums_sum = sum(nums)
return gauss_sum - nums_sum
318. Maximum Product of Word Lengths
Given a string array words
, find the maximum value of length(word[i]) * length(word[j])
where the two words do not share common letters. You may assume that each word will contain only lower case letters. If no such two words exist, return 0.
Example 1:
Given ["abcw", "baz", "foo", "bar", "xtfn", "abcdef"]
Return 16
The two words can be "abcw", "xtfn"
.
Example 2:
Given ["a", "ab", "abc", "d", "cd", "bcd", "abcd"]
Return 4
The two words can be "ab", "cd"
.
Example 3:
Given ["a", "aa", "aaa", "aaaa"]
Return 0
No such pair of words.
相当然的解法是遍历列表配合 set, 结果必然超时了.
class Solution(object):
def maxProduct(self, words):
"""
:type words: List[str]
:rtype: int
"""
results = [0]
length = len(words)
for i in xrange(length):
item_i = words[i]
for item_j in words[i:]:
if len(set(item_i + item_j)) == len(set(item_i)) + len(set(item_j)):
results.append(len(item_i) * len(item_j)) return max(results)
两个 for, 复杂度是 O(n**2), 不用跑都知道会超时. 如果能降到 O(nlogn) 说不定还有戏. 那能知道什么时候该停下么? 不知道, 先过.
342. Power of Four
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
Example:
Given num = 16, return true. Given num = 5, return false.
Follow up: Could you solve it without loops/recursion?
tmp > 1 也就是最小值 >>= 到 4的0次幂, 也就是 1, 然后再还原回来. LeetCode: 70.80%
class Solution(object):
def isPowerOfFour(self, num):
"""
:type num: int
:rtype: bool
"""
if num < 1:
return False i, tmp = 0, num
while tmp > 1:
tmp >>= 2
i += 2 return num >> i << i == num
371. Sum of Two Integers
Calculate the sum of two integers a and b, but you are not allowed to use the operator +
and -
.
Example:
Given a = 1 and b = 2, return 3.
完全没想法, 过.
389. Find the Difference
Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.
Example:
Input:
s = "abcd"
t = "abcde" Output:
e Explanation:
'e' is the letter that was added.
没想法.
393. UTF-8 Validation
A character in UTF8 can be from 1 to 4 bytes long, subjected to the following rules:
- For 1-byte character, the first bit is a 0, followed by its unicode code.
- For n-bytes character, the first n-bits are all one's, the n+1 bit is 0, followed by n-1 bytes with most significant 2 bits being 10.
This is how the UTF-8 encoding would work:
Char. number range | UTF-8 octet sequence
(hexadecimal) | (binary)
--------------------+---------------------------------------------
0000 0000-0000 007F | 0xxxxxxx
0000 0080-0000 07FF | 110xxxxx 10xxxxxx
0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
0001 0000-0010 FFFF | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
Given an array of integers representing the data, return whether it is a valid utf-8 encoding.
Note:
The input is an array of integers. Only the least significant 8 bits of each integer is used to store the data. This means each integer represents only 1 byte of data.
Example 1:
data = [197, 130, 1], which represents the octet sequence: 11000101 10000010 00000001. Return true.
It is a valid utf-8 encoding for a 2-bytes character followed by a 1-byte character.
Example 2:
data = [235, 140, 4], which represented the octet sequence: 11101011 10001100 00000100. Return false.
The first 3 bits are all one's and the 4th bit is 0 means it is a 3-bytes character.
The next byte is a continuation byte which starts with 10 and that's correct.
But the second continuation byte does not start with 10, so it is invalid.
LeetCode Python 位操作 1的更多相关文章
- Leetcode Python Solution(continue update)
leetcode python solution 1. two sum (easy) Given an array of integers, return indices of the two num ...
- LeetCode python实现题解(持续更新)
目录 LeetCode Python实现算法简介 0001 两数之和 0002 两数相加 0003 无重复字符的最长子串 0004 寻找两个有序数组的中位数 0005 最长回文子串 0006 Z字型变 ...
- 【leetcode❤python】Sum Of Two Number
#-*- coding: UTF-8 -*- #既然不能使用加法和减法,那么就用位操作.下面以计算5+4的例子说明如何用位操作实现加法:#1. 用二进制表示两个加数,a=5=0101,b=4=0100 ...
- [LeetCode][Python]Container With Most Water
# -*- coding: utf8 -*-'''https://oj.leetcode.com/problems/container-with-most-water/ Given n non-neg ...
- python位操作(进制)与ascii
位操作符 位操作的操作符与python的set的操作符一样.与C语言中的位操作符也是一样的. a = 60 #60的二进制为 0011 1100b = 13 #13的二进制为 00001101 c = ...
- 【leetcode❤python】 7. Reverse Integer
#-*- coding: UTF-8 -*-#2147483648#在32位操作系统中,由于是二进制,#其能最大存储的数据是1111111111111111111111111111111.#正因为此, ...
- [Leetcode][Python]56: Merge Intervals
# -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 56: Merge Intervalshttps://oj.leetcode. ...
- [Leetcode][Python]55: Jump Game
# -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 55: Jump Gamehttps://leetcode.com/probl ...
- [Leetcode][Python]54: Spiral Matrix
# -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com' 54: Spiral Matrixhttps://leetcode.com/p ...
随机推荐
- .NET 高性能WEB架构-比较容易改造方式 - .NET架构
下面列出的一些,是我们常见而且比较容易去优化的方式,当然细节方面非常多,仅供参考: 1.数据库依然选择SQL Server数据库(最新的sqlserver功能是很强大的)和使用订阅发布进行单写多读的读 ...
- 算法题目-记hulu失败的实习面试
1.对于数组A[0,1,2,3,4,...,k],求得0<=i < j < k,且使得A[j] - A[i]为最大值. 最简单也最容易想到的搜索两遍,即可得到答案.i的位置从起始至倒 ...
- 深入浅出WPF之Binding的使用(一)
在WPF中Binding可以比作数据的桥梁,桥梁的两端分别是Binding的源(Source)和目标(Target).一般情况下,Binding源是逻辑层对象,Binding目标是UI层的控件对象:这 ...
- DependencyProperty属性介绍
1 DependencyProperty从属属性 1. 从属属性要定义为静态.为了在外部可以绑定,最好定义为Public 2. 从属属性实际上是取代了正常属性的存值变量 3. ...
- FPAG结构 组成 工作原理 开发流程(转)
FPGA组成.工作原理和开发流程 备注:下面的描述基于ALTERA系列的FPGA芯片,而且是第一次学习FPGA,其中的一部分内容是参考一些资料总结的,个人独特的分析和见解还偏少. 1. FPGA概述 ...
- jenkins之-----------在必要的时候并发构建
jenkins支持在同一节点支持同任务并发,但存在形成报告时会覆盖相应的文件,查看官网后发现有介绍“在必要的时候并发构建” 大致意思就是:将此项勾选后,可以同时执行,执行在任务自己的workspace ...
- 交换机多VLAN访问同一网络
一.前言 经常有需求通过交换机改变IP地址或者实现在同一个交换机中建立多个VLAN访问外部网络(VLAN之间独立),在折腾了多次后,稍有心得,现记录之. 二.实现方案 何为VLAN就不在此赘述.实现起 ...
- select、poll和epoll的比较
一.select机制 在linux下网络通信中,经常用到select机制,这是一种异步通信的实现方式,select中提供一fd_set的数据结果,实际上是一个long类型的数组, 每一个数组元素都能与 ...
- FZU2110 Star【计算几何】
Overpower often go to the playground with classmates. They play and chat on the playground. One day, ...
- python2和python3的不同
1.性能 Py3.0运行 pystone benchmark的速度比Py2.5慢30%.Guido认为Py3.0有极大的优化空间,在字符串和整形操作上可 以取得很好的优化结果. Py3.1性能比Py2 ...