2022-3-10 剑指offer day28

题1:

JZ3 数组中重复的数字

描述

在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组[2,3,1,0,2,5,3],那么对应的输出是2或者3。存在不合法的输入的话输出-1
 
数据范围:0\le n \le 10000 \0n10000 
进阶:时间复杂度O(n)\O(n) ,空间复杂度O(n)\O(n) 
 1 import java.util.*;
 2 
 3 
 4 public class Solution {
 5     /**
 6      * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 7      *
 8      * 
 9      * @param numbers int整型一维数组 
10      * @return int整型
11      */
12     public int duplicate (int[] numbers) {
13         // write code here
14         Set<Integer> set=new HashSet<>();
15         for (int x:numbers) {
16             if (!set.contains(x)) set.add(x);
17             else return x;
18         }
19         return -1;
20     }
21 }

思路:集合。遍历。

 

题2:

JZ51 数组中的逆序对''

描述

在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将P对1000000007取模的结果输出。 即输出P mod 1000000007

数据范围:  对于 50\%50% 的数据, size\leq 10^4size104
对于 100\%100% 的数据, size\leq 10^5size105
数组中所有数字的值满足 0 \le val \le 10000000val1000000

要求:空间复杂度 O(n)O(n),时间复杂度 O(nlogn)O(nlogn)

输入描述:

题目保证输入的数组中没有的相同的数字
 1 import java.util.*;
 2 
 3 public class Solution {
 4     public int InversePairs(int [] array) {
 5         int[] sortedarr=new int[array.length];
 6         sortedarr[0]=array[0];
 7         int sum=0,len=1;
 8         for (int i=1;i<array.length;i++) {
 9             int insert=binarySearch(sortedarr,0,len,array[i]);
10             sum+=len-insert;
11             len++;
12             sum%=1000000007;
13         }
14         return sum;
15     }
16     
17     public int binarySearch(int[] arr,int l,int r,int target){
18         int len=r;
19         while (l<r) {
20             int mid=(l+r)/2;
21             if (target>arr[mid]) {
22                 l=mid+1;
23             }else {
24                 r=mid;
25             }
26         }
27         int res=l;
28         for (int i=len;i>res;i--) {
29             arr[i]=arr[i-1];
30         }
31         arr[res]=target;
32         return res;
33     }
34 }

思路:维护一个数组。根据插入的索引计算逆序对。

posted on 2022-03-10 10:32  阿ming  阅读(19)  评论(0)    收藏  举报

导航