算法的核心是:计算当前数和前一个数的差值,用该差值和以前最小的连续数的差值作比较;如果当前的差值更小,则发现了更小的连续数的差值;如果当前的差值更大,则沿用以前的最小连续数差值作为新的最小连续数差值。
MinDiffBetweenNeighborNumbersTest.java:
-
-
- import java.util.Random;
-
-
- public class MinDiffBetweenNeighborNumbersTest {
-
- public static void main(String[] args) {
- Random random = new Random();
- int[] nums = {1,10,11,2,5,7,9,100,200,200,300};
- int length = nums.length;
- // 99,98 2,1 52,51 66,63
-
- // 求相差最小的2个相邻的数的差值( 即相差的绝对值 )
- int[][] dp = new int[length][3];
- // dp[i][0] 存储的是较大的数
- // dp[i][1] 存储的是较小的数
- // dp[i][2] 存储的是两数差值的绝对值
- for (int i = 0; i < length; i++) {
- int num = nums[i];
- if( i==0 ){
- dp[i][0] = num;
- dp[i][1] = num;
- dp[i][2] = 0;
- }else{
- int num_prev = nums[i-1];
- if( i == 1 ){
- if( num > num_prev ){
- dp[i][0] = num;
- dp[i][1] = num_prev;
- }else {
- dp[i][0] = num_prev;
- dp[i][1] = num;
- }
- dp[i][2] = Math.abs( num - num_prev );
- }else {
- // 计算当前数和前一个数的差值,用该差值和以前最小的连续数的差值作比较;如果当前的差值更小,则发现了更小的连续数的差值;如果当前的差值更大,则沿用以前的最小连续数差值作为新的最小连续数差值
- int diff = Math.abs(num - num_prev);
- int diff_prev = dp[i - 1][2];
- if( diff < diff_prev){
- if( num> num_prev ){
- dp[i][0]= num;
- dp[i][1]= num_prev;
- }else {
- dp[i][0]= num_prev;
- dp[i][1]= num;
- }
- dp[i][2] = diff;
- }else {
- dp[i][0] = dp[i-1][0];
- dp[i][1] = dp[i-1][1];
- dp[i][2] = diff_prev;
- }
- }
- }
- }
- int[] result = dp[length - 1];
- System.out.println( result[0] + " 和 " + result[1] + " 相差 " + result[2] );
- }
- }