剑指offer-面试题36-数组中的逆序对(O(n)复杂度)
来源:互联网 发布:sql 选取第三大 编辑:程序博客网 时间:2024/06/05 11:38
题目:在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。
例: 在数组{7,5,6,4}中,一共存在5个逆序对,分别是(7,6),(7,5),(7,4),(6,4),和(5,4)
剑指offer中提供了一种O(nlogn)的解法,此处提供一种O(n)的解法
public class Solution { /* 思路如下: 借助一个数组hash,统计array从后往前的情况下,到第i位时候,i后面每个数字出现的次数 1. 从后往前遍历array, hash数组记录数字array[i]已出现的次数 2. 对于数字array[i],统计 array[x](此处 x>i)的的部分,小于array[i]的数字总数 count count 等于hash数组中 hash[x]的和(此处 x < array[i]) 3. count即为 array 数组中, 以第i位开始的子数组的逆序数 */ public int InversePairs(int [] array) { if(array == null || array.length == 0) return 0; int[] hash = new int[10]; int i = array.length-1; int ans = 0; for(; i>= 0; i--){ hash[array[i]] ++; ans += countInversePairs(hash, array[i]); } return ans; } private int countInversePairs(int[] hash, int target){ int count = 0; for(int i = 0; i < target; i++){ count += hash[i]; } return count; } }
0 0
- 剑指offer-面试题36-数组中的逆序对(O(n)复杂度)
- 剑指offer-面试题36-数组中的逆序对(O(n)复杂度)
- 剑指offer面试题36:数组中的逆序对
- [剑指offer][面试题36]数组中的逆序对
- 【剑指offer】面试题36:数组中的逆序对
- 剑指Offer:面试题36 数组中的逆序对
- 剑指offer 面试题36:数组中的逆序对
- 剑指offer 面试题36—数组中的逆序对
- 【剑指Offer学习】【面试题36:数组中的逆序对】
- 剑指offer-面试题36:数组中的逆序对
- 剑指offer之面试题36数组中的逆序对
- 剑指offer面试题36-数组中的逆序对
- 剑指offer面试题36:数组中的逆序对
- 剑指Offer----面试题36:数组中的逆序对
- 剑指Offer面试题36:数组中的逆序对
- 剑指offer--面试题36:数组中的逆序对
- 剑指Offer之面试题36:数组中的逆序对
- 剑指Offer---面试题36:数组中的逆序对
- bat中调用另外一个bat
- java.lang.IllegalStateException此种错误为springmvc的requestmapping在一个controller中重复的原因
- iOS开发多线程篇—GCD介绍
- HashMap 原理浅析
- keras系列二(补充)theano的tensor库
- 剑指offer-面试题36-数组中的逆序对(O(n)复杂度)
- Leetcode - Palindrome Linked List
- Linux IP代理筛选系统(shell+proxy)
- html img Src base64 图片显示
- XP+IIS5.1+MVC4 发布网站
- 数学竖式排版中不为人知的技巧
- [从头学数学] 第203节 坐标系与参数方程
- FreeRTOS高级篇2---FreeRTOS任务创建分析
- Spring 事务管理@Transactional