Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 2eb6e15

Browse files
committed
add 0493 folder & cpp vserion
1 parent dda367b commit 2eb6e15

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
class Solution {
2+
private:
3+
inline bool cmp1(vector<int>::iterator a,
4+
vector<int>::iterator b)
5+
{
6+
if (*a >= 0 && *b >= 0)
7+
{
8+
const unsigned ua = *a, ub = *b ;
9+
return ua <= (ub << 1) ;
10+
}
11+
12+
if (*a < 0 && *b < 0)
13+
{
14+
const unsigned ua = -*a, ub = -*b ;
15+
return ua >= (ub << 1) ;
16+
}
17+
18+
if (*a < 0 && *b >= 0)
19+
return true ;
20+
21+
if (*a >= 0 && *b < 0)
22+
return false ;
23+
}
24+
25+
unsigned CountLRPairs(vector<int>::iterator start,
26+
vector<int>::iterator end)
27+
{
28+
if (start + 1 >= end)
29+
return 0 ;
30+
if (start + 2 == end)
31+
{
32+
if (*start <= *(start+1))
33+
return !cmp1(start, start+1) ; // 这里也要计算,应为可能有负数
34+
else // 这边也要排序,需要特别注意排序的条件是a[i] < a[j],而逆序的条件是a[i] < 2*a[j]
35+
{
36+
swap(*start, *(start+1)) ;
37+
return !cmp1(start+1, start) ; // 交换过位置了
38+
}
39+
}
40+
41+
vector<int>::iterator mid = start + ((end-start) >> 1) ;
42+
vector<int>::iterator pF = start, pB = mid ;
43+
int cnt = CountLRPairs(start, mid) + CountLRPairs(mid, end) ;
44+
while (pF != mid)
45+
{
46+
while (pB != end && !cmp1(pF, pB))
47+
++pB ;
48+
cnt += pB-mid ;
49+
++pF ;
50+
}
51+
52+
vector<int> tmp(start, mid) ;
53+
pF = tmp.begin() ;
54+
pB = mid ;
55+
vector<int>::iterator p = start ;
56+
57+
auto size = end - start ;
58+
if (size == 10)
59+
++size ;
60+
61+
while (pF != tmp.end() && pB != end)
62+
{
63+
if (*pF <= *pB)
64+
*p++ = *pF++ ;
65+
else
66+
*p++ = *pB++ ;
67+
}
68+
while (pF != tmp.end())
69+
*p++ = *pF++ ;
70+
while (pB != end)
71+
*p++ = *pB++ ;
72+
73+
return cnt ;
74+
}
75+
public:
76+
int reversePairs(vector<int>& nums) {
77+
return CountLRPairs(nums.begin(), nums.end()) ;
78+
}
79+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /