# 算法-在数组中如何快速找出顺序不对的值

### 评论（9）

2017-10-16 9 楼

1 2 3 4 5 6 10 11 7 8 9
1 2 3 4 7 8 9 10 5 6 11

1 2 3 4 7 8 9 10 5 11

(a_0, a_1), (a_1, a_2), ...

1. 有公共元素，即a_k+1 = a_m

int k = -1, m = -1;
int err1, err2; //Return Value
for(int i = 0; i < 99; i++)
{
if(a[i] > a[i+1])
{
if(k == -1)
k = i;
else
m = i;
}
}
//if(k == -1)
if(m == -1)
{
if(k == 0 || a[k-2] > a[k+1])
{
//if(k == 98)
//throw new Exception("Error: find one only");
err1 = k + 1;
err2 = k + 2;
}
else
{
err1 = k - 1;
err2 = k;
}
}
else if(m == k + 1)
{
if(k + 3 >= 100 || a[k] < a[k+3])
{
err1 = k + 1;
err2 = k + 2;
}
else if(k == 0 || a[k-1] < a[k+2])
{
err1 = k;
err2 = k + 1;
}
else
{
err1 = k;
err2 = k + 2;
}
}
else
{
if(k == 0 || a[k-1] < a[k+1])
{
err1 = k;
}
else
{
err1 = k + 1;
}
if(a[m-1] < a[m+1])
{
err2 = m;
}
else
{
err2 = m + 1;
}
}

2017-10-07 8 楼

2017-09-26 7 楼

1 2 3 4 5 6 10 11 7 8 9其实并没有歧义

2017-09-14 6 楼

1.n位置的值比n-1,n+1位置的值都小
2.n位置的值比n-1,n+1位置的值都大

2017-08-18 5 楼

\$arr = array();
for(\$i=0;\$i<100;\$i++){
\$arr[\$i]=\$i;
}
\$arr[59] = 200;
\$arr[87] = 150;

\$count = count(\$arr);
\$pre_wrong = -1;
\$end_wrong = -1;
\$c = 0;
for(\$i=0;\$i<\$count;\$i++){
if(\$pre_wrong==-1)
if(\$arr[\$i]>\$arr[\$i+1]){
\$pre_wrong=\$i;
\$i+=2;
}
if(\$end_wrong==-1)
if(\$arr[\$i]<\$arr[\$i-1])
\$end_wrong = \$i-1;
\$c++;
if(\$pre_wrong!=-1 && \$end_wrong!=-1) break;
}
var_dump(\$pre_wrong,\$end_wrong,\$c); //\$c为查找的次数

int(59) int(87) int(87)

2017-08-17 4 楼

function getWrongNum(int[] arr){
int arr_counter = count(arr);
int pre_wrong_num = -1;
int end_wrong_num = -1;
for(int i=0; i<arr_counter/2+1; i++){
if(pre_wrong_num == -1)
if(arr[i]>arr[i+1])
pre_wrong_num = i;
if(end_wrong_num = -1)
if(arr[i]<arr[i-1])
end_wrong_num = i;
}
int[] result = {pre_wrong_num, end_wrong_num};
return result;
}

2017-08-15 3 楼

1 2 3 5 4 6

int get_wrong_num(int arr[], int len, int wrong_index_arr[])
//arr传入的是所要测试的数组，len是数组长度，wrong_index_arr是存放错误位置的标号
{
int i = 0;
int k = 0;

if (arr[0] > arr[1])
{
if (arr[1] < arr[2])
{
wrong_index_arr[k++] = 0;
}
else
{
wrong_index_arr[k++] = 1;
}
}
i = 1;
while ((i < len - 1) && (k < WRONGSIZ)) /*这里设置了一个宏WRONGSIZ 其值这里为2*/
{
if (arr[i] > arr[i+1])
{
if (arr[i+1] > arr[i-1])
{
wrong_index_arr[k++] = i;
}
else
{
wrong_index_arr[k++] = i + 1;
}
i++;
}
i++;
}
if (k < WRONGSIZ)
{
wrong_index_arr[k] = wrong_index_arr[k-1];
wrong_index_arr[k-1] = wrong_index_arr[k-1]-1;
}

return 0;
}

2017-08-04 2 楼

2017-07-07 1 楼

arr = {11,22,33,44,55,66,44,12,1024}; //如果超过2个 则new 一个ArrayList保留结果 不断刷新first的值
int first = -1 ,second;
for(int i = 0 ; first < arr.length() ; i++ )
{
if(arr[i] <= arr[i+1]) continue;
else
{
first = i;
if(first==-1) second = first;
continue;
}
}

int temp = first;
first = second;
second = temp; #done

1958 主题
5719 回复
19040 人气