题目描述
在一个字符串(0<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置, 如果没有则返回 -1(需要区分大小写).(从0开始计数)
思路
利用归并排序中的–前面的值大于后面的值交换即为逆序对,从而找出逆序对的对
代码
public class Solution {
int num;
public int InversePairs(int [] array) {
if(array == null || array.length == 0) return 0;
int[] temp = new int[array.length];
mergeSort(array,0,array.length - 1,temp);
return num;
}
public void mergeSort(int[] array,int left,int right,int[] temp){
if(left < right){
int mid = left + (right - left) / 2;
mergeSort(array,left,mid,temp);
mergeSort(array,mid+1,right,temp);
merge(array,left,mid,right,temp);
}
}
public void merge(int[] array,int left,int mid,int right,int[] temp){
int i = left;
int j = mid + 1;
int t = 0;
while(i <= mid && j <= right){
if(array[i] <= array[j]){
temp[t++] = array[i++];
}else{//此时前面的数大于后面的数,就构成了题干中的条件
temp[t++] = array[j++];
//由于排序的原因,可以以最后的两段为例说明,最后的两段都是排好序的,如果array[i]>array[j],那么i-mid之间的数都会大于arr[j],也就是i-mid之间的数与arr[j]都能构成逆序对
//则必然i-mid之间的数都大于array[j]
num = (num + (mid - i + 1)) % 1000000007;
}
}
while(i <= mid){
temp[t++] = array[i++];
}
while(j <= right){
temp[t++] = array[j++];
}
t = 0;
int tempLeft = left;
while(tempLeft <= right){
array[tempLeft++] = temp[t++];
}
}
}