Skip to content

Commit 2d67a5b

Browse files
committed
add leetcode:offer-43-51
1 parent 7b274c7 commit 2d67a5b

File tree

4 files changed

+69
-0
lines changed

4 files changed

+69
-0
lines changed

Algorithm/src/acwing/basic/chapter1/_788ReverseOrderNumber.java

+6
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ public static void main(String[] args) throws IOException {
4949
}
5050

5151
public static long mergeSort(int[] q, int l, int r) {
52+
// 为什么返回0:遍历到最深的一层,也就是只有一个数的时候,自然逆序对就是0!!!!
5253
if (l >= r) return 0;
5354
int mid = l + r >> 1;
5455
// res答案必须定义成long,不然过不了
@@ -57,6 +58,11 @@ public static long mergeSort(int[] q, int l, int r) {
5758
while (i <= mid && j <= r) {
5859
if (q[i] <= q[j]) temp[k++] = q[i++];
5960
else {
61+
62+
/*注意这里是mid-i+1 , 不是res++
63+
这道题是归并的变形,根据逆序对的定义,我们可以发现排序的第二种情况:左半边的起始值到i这部分都
64+
大于右半边的mid。 所以直接用左半边的右边界mid - i(起始处)+1 就可以得到当前逆序对的数量。
65+
*/
6066
res += mid - i + 1;
6167
temp[k++] = q[j++];
6268
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package offer;
2+
3+
/**
4+
* @author : CodeWater
5+
* @create :2022-07-28-22:06
6+
* @Function Description :43. 1~n 整数中 1 出现的次数
7+
*/
8+
public class _43TheNumberOfTimesAppearingInN {
9+
class Solution {
10+
public int countDigitOne(int n) {
11+
int digit = 1 , res = 0;
12+
int high = n / 10 , cur = n % 10 , low = 0 ;
13+
while( high != 0 || cur != 0 ){
14+
if( cur == 0 ) res += high * digit ;
15+
else if( cur == 1 ) res += high * digit + low + 1;
16+
else res += (high + 1) * digit ;
17+
low += cur * digit;
18+
cur = high % 10;
19+
high /= 10;
20+
digit *= 10;
21+
}
22+
return res;
23+
}
24+
}
25+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package offer;
2+
3+
/**
4+
* @author : CodeWater
5+
* @create :2022-07-28-17:20
6+
* @Function Description :51.数组中的逆序对
7+
*/
8+
public class _51InsteadInTheArray {
9+
class Solution {
10+
int[] temp ;
11+
public int reversePairs(int[] nums) {
12+
if( nums.length == 0 ) return 0;
13+
temp = new int[nums.length];
14+
return mergeSort( nums , 0 , nums.length - 1 );
15+
}
16+
17+
public int mergeSort( int[] nums , int l , int r ){
18+
if( l >= r ) return 0;
19+
int mid = l + r >> 1 ;
20+
int res = mergeSort(nums , l , mid ) + mergeSort( nums , mid + 1 , r );
21+
int k = 0 , i = l , j = mid + 1;
22+
while( i <= mid && j <= r ){
23+
if( nums[i] <= nums[j] ) temp[k++] = nums[i++];
24+
else{
25+
res += mid - i + 1;
26+
temp[k++] = nums[j++];
27+
}
28+
}
29+
while( i <= mid ) temp[k++] = nums[i++];
30+
while( j <= r ) temp[k++] = nums[j++];
31+
32+
33+
for( i = l , j = 0 ; i <= r ; i++ , j++ )
34+
nums[i] = temp[j];
35+
return res;
36+
}
37+
}
38+
}
Binary file not shown.

0 commit comments

Comments
 (0)