Leetcode Python bit Operation 1

Source: Internet
Author: User
Tags bitwise

Python bit operation:

Bitwise AND &, Bitwise OR |

Don't realize

Bitwise XOR or ^

num ^ num = 0

Shift left <<

num << 1 = = num * 2**1

Shift Right >>

num >> 2 = = Num/2**2

Take counter ~

~num = =-(num + 1)

1. Single number

Given an array of integers, every element appears twice except for One. Find the single One.

Note:
Your algorithm should has a linear runtime Complexity. Could you implement it without using extra memory?

The key point is that the same integer bitwise XOR is 0, the integer and 0 are different or unchanged, and a reduce is DONE. Leetcode execution efficiency beats 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 the single One.

Note:
Your algorithm should has a linear runtime Complexity. Could you implement it without using extra memory?

The solution of the next three ways, if you see this answer, you should ask the sum and set the time space complexity of how many, why. 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, unsigned integer.

For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represent Ed in binary as 00111001011110000010100101000000).

Follow up:
If This function is called many times, what would you optimize it?

first, Python has no native support for the unsigned integer, and secondly, This is the same solution for the next three paths. Leetcode:85.2%.

class solution:     # @param n, an integer    # @return an integer    def reversebits (self, n):         = bin (n)        if n >= 0:            = string[:2] + string[2:].zfill (+) [:: -1]         Else :             = string[:3] + string[3:].zfill (+) [:: -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 weigh T).

For example, the 32-bit integer ' One ' 00000000000000000000000000001011 has a binary representation, so the function should return 3.

This brush question does not mean anything, count of the time space complexity is how Much. Leetcode:62.81%.

class Solution (object):     def hammingweight (self, n):         """         : type n:int        : rtype:int        "        " "= bin (n)          Return String.count ("1")

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, inclus Ive.

For example, given the range [5, 7], and you should return 4.

If you use range, you will be reported out of memory, with Xrange will be reported Time-out. I brought [0, 2147483647] myself and did not Run.

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))

To observe, the key is that the log (n, 2) is much larger than log (m, 2), if it is greater than 1, then it must be 0, if less than 1, then Reduce. Leetcode:2.52%.

classSolution (object):defrangebitwiseand (self, m, n):""": Type M:int:type n:int:rtype:int"""        ifm = =0:return0 fromMathImportLog Logm= Log (m, 2) Logn= Log (n, 2)                ifLOGN-LOGM >= 1:            return0returnReduceLambdax,y:x&y, xrange (m, n+1))

The use of log is obvious cheating, and then follow the idea, before all from the beginning of m, now think from n, because & operation will make N rapid decline, two cases, one is to traverse [m, n] of the &, and the other half of the way there are 0 Out. and, I believe that the time-consuming large should be xrange, the bit operation itself should be quick. Leetcode:70.18%.

class Solution (object):     def rangebitwiseand (self, m, n):         """         : type m:int        : type n:int        : rtype:int        "" "while         m < n:< c16/>&= n-1                    return n

Increase if n = = 0 judgment, If it is 0 break, see how much to Improve. Leetcode:73.09%.

class Solution (object):     def rangebitwiseand (self, m, n):         """         : type m:int        : type n:int        : rtype:int        "" "while         m < n:< c16/>&= n-1            if n = = 0                :break                    return n

6. Power of

Given an integer, write a function to determine if it is a power of.

first, 2 of the 0 is 1, so n >= 1, then, is the n execution >>= i, if n is the power of 2, then n >> i << i = = n, Note Our goal is to calculate I let n &G t;> i = = 2, so i-1. Leetcode:45.27%.

class Solution (object):     def ispoweroftwo (self, n):         """         : type n:int        : rtype:bool        "" "        if n < 1:              return  False                = 0, n while          m:            >>= 1            + = 1            return n >> (i-1) << (i-1) = = N

260. Single number III

Given An array of numbers nums , in which exactly-elements appear only once and all the other elements appear exactly Twice. Find the elements that appear only once.

For example:

Given nums = [1, 2, 1, 3, 2, 5] , return [3, 5] .

Note:

    1. The order of the result is not Important. The above example, is [5, 3] also correct.
    2. Your algorithm should run in linear runtime Complexity. Could implement it using only constant space complexity?

The first is the solution of the next three ways, must be timed out

 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 

Should still be in the study bit operation, the same number becomes 0 and different the same number left. If global xor, The final value is two digits of the Xor. This involves the operation of the details in place, not come Out.

I'm not going to use a bitwise operation to solve this problem, collections there is a Counter class in this library, and the parameters are iterable objects that count the Hashable objects in the Object.

Sorted can sort the values of a dictionary. Leetcode:45.7%.

class Solution (object):     def singlenumber (self, nums):         """         : type nums:list[int]        : rtype:list[int]        "" "from        Import  Counter        = Counter (nums)        return 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 and That's missing from the Array.

For example,
Given nums = [0, 1, 3] return 2 .

Note:
Your algorithm should run in linear runtime Complexity. Could implement it using only constant extra space complexity?

The sum of arithmetic progression, leetcode:78.18%.

class Solution (object):     def missingnumber (self, nums):         """         : type nums:list[int]        : rtype:int        "        " "= len (nums)        = length * (length-1)/2 + length        = sum (nums)        return Gauss_sum-nums_ Sum

318. Maximum Product of Word Lengths

Given A string array words , find the maximum value of the where the words does not length(word[i]) * length(word[j]) share common Letters. You may assume this each word would contain only lower case letters. If no such and words exist, return 0.

Example 1:

Given["abcw", "baz", "foo", "bar", "xtfn", "abcdef"]
Return16
The both words can be "abcw", "xtfn" .

Example 2:

Given["a", "ab", "abc", "d", "cd", "bcd", "abcd"]
Return4
The both words can be "ab", "cd" .

Example 3:

Given["a", "aa", "aaa", "aaaa"]
Return0
No such pair of WORDS.

Quite a solution is to traverse the list with set, and the result must be timed Out.

classSolution (object):defmaxproduct (self, words):""": Type words:list[str]: rtype:int"""Results=[0] Length=Len (words) forIinchxrange (length): item_i=words[i] forItem_jinchwords[i:]:ifLen (set (item_i + item_j)) = = Len (set (item_i)) +len (set (item_j)): results.append (len (item_i)*Len (item_j))returnMax (results)

Two for, the complexity is O (n**2), do not run all know will time Out. If you can drop to O (nlogn) maybe there is a chance. Do you know when it's time to stop? I don't know, i'll go first.

342. Power of Four

Given an integer (signed), write a function to check whether it is a power of 4.

Example:
Given num = +, return True. Given num = 5, return false.

Follow up:could you solve it without loops/recursion?

TMP > 1 is the minimum value of >>= to 4 of the 0 power, that is, 1, and then restore Back. leetcode:70.80%

class Solution (object):     def ispoweroffour (self, num):         """         : type num:int        : rtype:bool        "" "        if num < 1:             return False                 = 0, num        whiletmp > 1:            >>= 2            + = 2                 return num >> i << i = = num

371. Sum of integers

Calculate the sum of of the integers a and b, but is not allowed to use the operator + and - .

Example:
Given a = 1 and b = 2, return 3.

No idea at all, Too.

389. Find The Difference

Given strings s and T which consist of only lowercase letters.

String t is generated by the random shuffling string s and then add one more than letter at a random Position.

Find the letter is added in t.

Example:

Input:s = "abcd" t = "abcde" output:eexplanation: ' e ' is the letter, the was Added.

No Idea.

Leetcode Python bit Operation 1

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.