[LintCode] 逆序对 Reverse Pairs
2016-04-26 16:11
519 查看
在数组中的两个数字如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。给你一个数组,求出这个数组中逆序对的总数。
概括:如果a[i] > a[j] 且 i < j, a[i] 和 a[j] 构成一个逆序对。
样例
序列 [2, 4, 1, 3, 5] 中,有 3 个逆序对 (2, 1), (4, 1), (4, 3),则返回 3 。
For an array A, if i < j, and A [i] > A [j], called (A [i], A [j]) is a reverse pair.
return total of reverse pairs in A.
Example
Given A = [2, 4, 1, 3, 5] , (2, 1), (4, 1), (4, 3) are reverse pairs. return 3
此处使用暴力法,似乎改用归并排序的思想。mark下回头研究下。
概括:如果a[i] > a[j] 且 i < j, a[i] 和 a[j] 构成一个逆序对。
样例
序列 [2, 4, 1, 3, 5] 中,有 3 个逆序对 (2, 1), (4, 1), (4, 3),则返回 3 。
For an array A, if i < j, and A [i] > A [j], called (A [i], A [j]) is a reverse pair.
return total of reverse pairs in A.
Example
Given A = [2, 4, 1, 3, 5] , (2, 1), (4, 1), (4, 3) are reverse pairs. return 3
此处使用暴力法,似乎改用归并排序的思想。mark下回头研究下。
public class Solution { /** * @param A an array * @return total of reverse pairs */ public long reversePairs(int[] A) { if(null == A || A.length <= 1) return 0; long count = 0l; for(int i = 0; i < A.length-1; i++) { for(int j = i+1; j < A.length; j++) { if(A[i] > A[j]) count++; } } return count; } }
相关文章推荐
- Leetcode 11. Container With Most Water
- RAID级别与规范
- RAID级别与规范
- Chain of Responsibility模式
- rails 提供下拉框select和select_tag用法(附加form_for, form_tag提交表单的内容)
- net::ERR_PROXY_CONNECTION_FAILED
- 异常:HibernateOptimisticLockingFailureException StaleStateException
- Debug Assertion Failed! Expression: _pFirstBlock == pHead
- 在CI框架中如何发送email?
- SendKeys.SendWait
- LightOJ 1138 Trailing Zeroes (III)
- View结合组策略进行应用程序下发
- [LintCode] Reverse Pairs 翻转对
- raise RuntimeError("autoconf error") RuntimeError: autoconf error
- MailMessage+SmtpClient 发送邮件
- DAY6:leetcode #11 Container With Most Water
- linker command failed with exit code 1 (use -v to see invocation)错误调试
- cpu_relax( )-----对自选循环等待(spin-wait loops)操作的优化【转】
- mac os 终端提示 you have new mail
- 人工智能对战游戏程序会怎样?奥创大战贾维斯吗!