试试这个。当最小的数字是第一个时,第二个条件用于捕获事件
int[] elements = {-5, -4, 0, 2, 10, 3, -3}; int smallest = Integer.MAX_VALUE; int secondSmallest = Integer.MAX_VALUE; for (int i = 0; i < elements.length; i++) { if(elements[i]==smallest){ secondSmallest=smallest; } else if (elements[i] < smallest) { secondSmallest = smallest; smallest = elements[i]; } else if (elements[i] < secondSmallest) { secondSmallest = elements[i]; } }
UPD 由@Axel
int[] elements = {-5, -4, 0, 2, 10, 3, -3};int smallest = Integer.MAX_VALUE;int secondSmallest = Integer.MAX_VALUE;for (int i = 0; i < elements.length; i++) { if (elements[i] < smallest) { secondSmallest = smallest; smallest = elements[i]; } else if (elements[i] < secondSmallest) { secondSmallest = elements[i]; }}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)