个人刷Leetcode的一点解法,欢迎批评讨论,每日更新

GitHub:

https://github.com/seventheli/LeetCode-Practice

singleNumber

Core: A XOR B XOR A XOR C XOR B = C

class Solution(object):def singleNumber(self, nums):""":type nums: List[int]:rtype: int"""result = 0for each in range(len(nums)):result ^= nums[each]return result

reverseString

Core: Serializing String Value, then descending the list

class Solution(object):def reverseString(self, s):lst = []for i in range(len(s)):lst.append(s[-(i + 1)])lst = ''.join(lst)return lst

Nim GAME

Core: Second player only win when  total accoumt % 4 = 0

class Solution(object):def canWinNim(self, n):val = n % 4if val != 0:return Trueelse:return False

Counting Bits

Core:

Each time the value is 2^n
The different between the the first half and second half is only the first digit

Example with 7
0 to 7 is
000

----
001

----
010
011

----

100
101
110
111
The Second half is always "1+Second Half

class Solution(object):def countBits(self, num):val = [0]while len(val) <= num:val += [i + 1 for i in val]return val[:num + 1]

Sum of two integers

Core: Implementation of an array of Full Adder

class Solution(object):def half_adder(self, a, b):s = a ^ bcin = a & breturn s, cindef full_adder(self, a, b, cin):s1, c1 = self.half_adder(a, b)s2, c2 = self.half_adder(cin, s1)c_out = c1 | c2return s2, c_outdef getSum(self, a, b):mask = 1ci = 0sum_total = 0while mask <= 0x080000000:a1 = a & maskb1 = b & mask(s, ci) = self.full_adder(a1, b1, ci)sum_total = sum_total | sci <<= 1mask <<= 1print "s: " + str(s) + "     ci: " + str(ci)maximum = 0x7FFFFFFFmask = 0xFFFFFFFFif sum_total > maximum:sum_total = ~(sum_total ^ mask)return sum_total

Add Digits

Core:

Dr(n) = n -9floor((n-1)/9)

Reference: https://en.wikipedia.org/wiki/Floor_and_ceiling_functions

class Solution(object):def addDigits(self, num):""":type num: int:rtype: int"""if num == 0:return 0else:return num - 9 * int((num - 1) / 9)

Maximum Depth of Binary Tree

Core:

Recursion

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = Noneclass Solution(object):def maxDepth(self, root):""":type root: TreeNode:rtype: int"""return self.search(root, 0)def search(self, node, i):if node is None:return ielse:i += 1a = self.search(node.left, i)b = self.search(node.right, i)if a > b:return aelse:return b

Two Sum II

Core:

Binary Search, Ignoring repeat value

Remain: Squeeze is not suitable for this kind of scenes

class Solution(object):def twoSum(self, numbers, target):""":type numbers: List[int]:type target: int:rtype: List[int]"""if not numbers:return []for i in xrange(len(numbers)):if i > 0 and numbers[i-1] == numbers[i]:continueind1 = iind2 = len(numbers) - i -1while ind1 <= ind2:sumv = numbers[ind1] + numbers[ind2]if sumv == target:return [ind1+1, ind2+1]elif sumv > target:ind2 -= 1else:ind1 += 1

Find the Difference

Core: Sort,Serializing String Value

class Solution(object):def findTheDifference(self, s, t):""":type s: str:type t: str:rtype: str"""s = list(s)s.sort()t = list(t)t.sort()for i in range(len(s)):if s[i] != t[i]:return t[i]return t[len(t)-1]

Invert Binary Tree

Core: Recursion

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = Noneclass Solution(object):def invertTree(self, root):""":type root: TreeNode:rtype: TreeNode"""self.invert(root)return  rootdef invert(self, node):if node is not None:template = node.leftnode.left = node.rightnode.right = templateself.invert(node.left)self.invert(node.right)

singleNumber

Core: A XOR B XOR A XOR C XOR B = C, Use Bit with different value in the two single value to regist each value in list(otherwise, divide list with the regist bit)

Reference:https://discuss.leetcode.com/topic/21605/accepted-c-java-o-n-time-o-1-space-easy-solution-with-detail-explanations/2

class Solution(object):def singleNumber(self, nums):""":type nums: List[int]:rtype: List[int]"""result = [0, 0]x = 0for each in nums:x ^= each# x = result_1 XOR result_2x &= -xfor each in nums:if each & x == 0:result[0] ^= eachelse:result[1] ^= eachreturn result

Move Zeroes

class Solution(object):def moveZeroes(self, nums):""":type nums: List[int]:rtype: void Do not return anything, modify nums in-place instead."""real_i = 0for each in xrange(0,len(nums)):nums[real_i] = nums[each]if nums[real_i] != 0:real_i += 1for each in xrange(real_i, len(nums)):nums[each] = 0

Linked List Random Node

Core: Recursion, for elements in an unknow list, fisrt of all, get 1 elements as output, for the following recursion, use 1/n(current recursion deep +1) probablity to repeat output, in the end of the recursion, the probability that each elements saved in output value is 1/(recursion deep +1),otherwise, the probablity developing with the recursion deep developing.

from random import randomclass Solution(object):def __init__(self, head):"""@param head The linked list's head.Note that the head is guaranteed to be not null, so it contains at least one node.:type head: ListNode"""self.header = headdef getRandom(self):"""Returns a random node's value.:rtype: int"""head = self.headerindex = 1while head:if random() * index <= 1:value = head.valindex += 1head = head.nextreturn value

Product of Array Except Self

Core: Divide the multplication into two part( before self and after self)

class Solution(object):def productExceptSelf(self, nums):""":type nums: List[int]:rtype: List[int]"""output = [1] * len(nums)n = len(nums)template = 1for i in range(1, n):template = template * nums[i - 1]output[i] *= templatetemplate = 1for i in range(n - 2, -1, -1):template = template * nums[i + 1]output[i] *= templatereturn output

Delete Node in a Linked List

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = Noneclass Solution(object):def deleteNode(self, node):""":type node: ListNode:rtype: void Do not return anything, modify node in-place instead."""node.val = node.next.valnode.next = node.next.next

Ransom Note

Core: Hash two string

class Solution(object):def canConstruct(self, ransomNote, magazine):""":type ransomNote: str:type magazine: str:rtype: bool"""magazine_dir = {}for each in list(magazine):if magazine_dir.get(each) is not None:magazine_dir[each] += 1else:magazine_dir[each] = 1for each in list(ransomNote):if magazine_dir.get(each) is not None:magazine_dir[each] -= 1if magazine_dir[each] < 0:return Falseelse:return Falsereturn True

Intersection of two arrays

Core: data structure convertion

class Solution(object):def intersection(self, nums1, nums2):""":type nums1: List[int]:type nums2: List[int]:rtype: List[int]"""set1 = set(nums1)set2 = set(nums2)return list(set1 & set2)

Same True

Core: Use Stack to save the node order

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = Noneclass Solution(object):def isSameTree(self, p, q):""":type p: TreeNode:type q: TreeNode:rtype: bool"""if not p and not q: return Trueif not p or not q: return Falsestack_p = [p]stack_q = [q]while stack_p and stack_q:node_p = stack_p.pop()node_q = stack_q.pop()if node_p.val != node_q.val:return Falseif node_p.left and node_q.left:stack_p.append(node_p.left)stack_q.append(node_q.left)elif not node_p.left and not node_q.left:passelse:return Falseif node_p.right and node_q.right:stack_p.append(node_p.right)stack_q.append(node_q.right)elif not node_p.right and not node_q.right:passelse:return Falsereturn True

is Sub sequence

Core: Two Pointer, Serializing String Value

class Solution(object):def isSubsequence(self, s, t):"""
        :type s: str:type t: str:rtype: bool"""
        list_s = list(s)list_t = list(t)list_s.sort()list_t.sort()i = 0j = 0while i < len(list_s):if j >= len(list_t):return Falseif list_s[i] == list_t[j]:i += 1j += 1return True

Top K Frequent Element

Core:  Map the frequent and sort the map

class Solution(object):def topKFrequent(self, nums, k):""":type nums: List[int]:type k: int:rtype: List[int]"""dir_nums = {}for each in nums:if each in dir_nums:dir_nums[each] += 1else:dir_nums[each] = 1return sorted(dir_nums, key=dir_nums.get, reverse=True)[:k]

转载于:https://www.cnblogs.com/eli-ayase/p/5854762.html

Personal Leetcode solution(Python) 1~20相关推荐

  1. 每日一道leetcode(python)77. 组合

    每日一道leetcode(python)77. 组合 2021-08-25 给定两个整数 n 和 k,返回范围 [1, n] 中所有可能的 k 个数的组合.你可以按 任何顺序 返回答案.示例 1:输入 ...

  2. 每日一道leetcode(python)48. 旋转图像

    每日一道leetcode(python)48. 旋转图像 2021-07-27 给定一个 n × n 的二维矩阵 matrix 表示一个图像.请你将图像顺时针旋转 90 度. 你必须在 原地 旋转图像 ...

  3. 每日一道leetcode(python)1823. 找出游戏的获胜者

    每日一道leetcode(python)1823. 找出游戏的获胜者 2021-08-07 共有 n 名小伙伴一起做游戏.小伙伴们围成一圈,按 顺时针顺序 从 1 到 n 编号.确切地说,从第 i 名 ...

  4. 每日一道leetcode(python)844. 比较含退格的字符串

    每日一道leetcode(python)844. 比较含退格的字符串 2021-09-05 给定 S 和 T 两个字符串,当它们分别被输入到空白的文本编辑器后,判断二者是否相等,并返回结果. # 代表 ...

  5. 每日一道leetcode(python)695. 岛屿的最大面积

    每日一道leetcode(python)695. 岛屿的最大面积 2021-08-21 给定一个包含了一些 0 和 1 的非空二维数组 grid .一个 岛屿 是由一些相邻的 1 (代表土地) 构成的 ...

  6. 每日一道leetcode(python)876. 链表的中间结点

    每日一道leetcode(python)876. 链表的中间结点 2021-08-19 给定一个头结点为 head 的非空单链表,返回链表的中间结点.如果有两个中间结点,则返回第二个中间结点.示例 1 ...

  7. 每日一道leetcode(python)46. 全排列

    每日一道leetcode(python)46. 全排列 2021-08-25 给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 .你可以 按任意顺序 返回答案.示例 1:输入:nums ...

  8. leetcode与python进阶学习总结

    转自:leetcode与python进阶学习总结 l1是一个链表型,val是其属性,以下句子意义为如果l1不为空则取l1.val否则取0,节省代码空间,干净利落 x= l1.val if l1 els ...

  9. 强势回归!比 Python 快 20% 的 Pyston v2.0 来了!

    作者:Kevin Modzelewski 机器之心编译 比 Python 快 20% 的 Pyston v2.0 来了. 2014 年,Python 实现 Pyston 诞生.Pyston 的开发目标 ...

最新文章

  1. EBS服务重启脚本(应用和数据库)
  2. Android SlidingMenu 开源项目 侧拉菜单的使用(详细配置)
  3. adams2015安装教程
  4. 灾备理论-可靠的异地灾备
  5. log4j 源码解析_Log4j配置详解
  6. websockets_使用Java WebSockets,JSR 356和JSON映射到POJO的
  7. 基于RTP的QOS算法简介
  8. AngularJS中的过滤器(filter)
  9. HTML5 中的新特性:
  10. java button随机颜色_Javascript点击按钮随机改变数字与其颜色
  11. UVa 12206 (字符串哈希) Stammering Aliens
  12. ubuntu面板的图标混乱
  13. 安装使用dubbo-admin管理台进行服务监控和服务治理
  14. 阿里云 磁盘脱机处理
  15. dist包编译html_npm package开发指南-包内容篇
  16. 根据 轮播图背景色 自动填充剩余背景色的 走马灯
  17. C语言使用josn库解析数据
  18. 计算机应用软件弹窗消除,去除电脑弹窗广告的4种方法
  19. 安全模式解除android,手机安全模式怎么解除
  20. 618省心凑背后的新算法——个性化凑单商品打包购推荐

热门文章

  1. mysql如何将多条返回结果的一个字段合并成一条
  2. 实现option上下移动_ES6原生实战Uploader工具类(从设计到实现)
  3. 多维数组做参数,内存可以看做是线性的
  4. Table Store实时数据通道服务Go SDK快速入门
  5. Antd Mobile Design输入框组件InputItem错误显示方式封装
  6. 快速接入阿里云应用配置管理工具 轻松开启企业效率新时代
  7. Ubuntu 15.10 默认壁纸?
  8. 需要注意的一些Mysql语句
  9. JPA + Hibernate + PostgreSQL + Maven基本配置示例
  10. cocos2dx打飞机项目笔记三:HeroLayer类和坐标系