题目
来源于Mathwork上的Cody,Problem 29 - Nearest Numbers.
Given a row vector of numbers, find the indices of the two nearest numbers.
Examples:
[index1 index2] = nearestNumbers([2 5 3 10 0 -3.1])
index1 =
1
index2 =
3
[index1 index2] = nearestNumbers([-40 14 22 17])
index1 =
2
index2 =
4
Notes
The indices should be returned in order such that index2 > index1.
There will always be a unique solution.
代码
function [index1,index2] = nearestNumbers(A)
for i=1:length(A)-1
[M,I]=min(abs(A(i)-A(i+1:end)));
B(i,1)=i;
B(i,2)=I+i;
B(i,3)=M;
end
[~,I]=min(B(:,3));
index1=B(I,1);
index2=B(I,2);
end
其它优秀代码
function [index1 index2] = nearestNumbers(A)
[sorted sort_ind] = sort(A);
[~,min_ind] = min(diff(sorted));
sort(sort_ind(min_ind:min_ind+1));
index1 = ans(1);
index2 = ans(2);
end