[python]leetcode(315). Count of Smaller Numbers After Self
来源:互联网 发布:linux关闭nagle算法 编辑:程序博客网 时间:2024/06/06 06:32
problem
You are given an integer array nums and you have to return a new
counts array. The counts array has the property where counts[i] is the
number of smaller elements to the right of nums[i].Example:
Given nums = [5, 2, 6, 1]
To the right of 5 there are 2 smaller elements (2 and 1). To the right
of 2 there is only 1 smaller element (1). To the right of 6 there is 1
smaller element (1). To the right of 1 there is 0 smaller element.
Return the array [2, 1, 1, 0].
分析
最朴素的想法就是从左向右对每一个元素都检查右边有几个元素比它小,这样的时间复杂度是
那么关键就在于怎么快速的找到那个比num[i]小的元素中最大的那个?可以使用一个数组维持已遍历的元素,然后使用二分查找找到相应的元素并把当前元素加入。
#超过了90%class Solution(object): def countSmaller(self, nums): """ :type nums: List[int] :rtype: List[int] """ import bisect n = len(nums) ans = [None]*n tmp = [] for i in range(n-1, -1, -1): t = nums[i] pos = bisect.bisect_left(tmp, t) ans[i] = pos tmp.insert(pos, t) return ans
还有一种解法是使用二叉树维持存储的数字,思路和之前数组存储的方式差不多,
优点:不用移动数组中的元素
缺点:二叉树可能左右不平衡
- [python]leetcode(315). Count of Smaller Numbers After Self
- leetcode Count of Smaller Numbers After Self
- leetcode Count of Smaller Numbers After Self
- leetcode Count of Smaller Numbers After Self
- Count of Smaller Numbers After Self | LeetCode
- leetcode Count of Smaller Numbers After Self
- LeetCode Count of Smaller Numbers After Self
- [Leetcode]Count of Smaller Numbers After Self
- leetcode - Count of Smaller Numbers After Self
- leetcode:Count of Smaller Numbers After Self
- 【Leetcode】Count of Smaller Numbers After Self
- 【leetCode】 Count of Smaller Numbers After Self
- [Leetcode] Count of Smaller Numbers After Self
- LeetCode -- Count of Smaller Numbers After Self
- Leetcode Count of Smaller Numbers After Self
- LeetCode -- Count of Smaller Numbers After Self
- LeetCode-Count of Smaller Numbers After Self
- LeetCode—315 Count of Smaller Numbers After Self
- textarea还剩余字数统计
- 【Java面试题】springMVC的原理?
- sql复制表定义及复制数据行
- hibernate中核心接口Query的用法简介
- python3的递归深度
- [python]leetcode(315). Count of Smaller Numbers After Self
- 字符串排序先导 键索引计数法 (c++ )
- GitChat · 运维 | 深入了解 Azure 云平台容器技术服务
- Elasticsearch之elasticsearch5.x 新特性
- 跳转语句,如果是pc访问就127.0.0.1
- 【Audio】耳机错误/频繁插入造成的无法识别
- 博客园 首页 新随笔 联系 订阅 管理 Ubuntu 16.04搭建LAMP开发环境 1. 配置网络环境 略 2. 设置ROOT密码 sud
- echarts2-网络动态攻击(带涟漪效果)
- 经验分享 | 【PDF下载】大数据峰会之MaxCompute数据上云与生态