数组翻转的一道题目

老赵博客里面的一道题目,以下是个人答案:

 1 /**

 2      * Besides this,stack could be used to solved it.

 3      * @param array

 4      * @param begin

 5      * @param end

 6      * @throws Exception

 7      */

 8     public static void Reverse(int[] array,int begin,int end) throws Exception{

 9         

10         if(array==null)

11             throw new NullPointerException("Array is null"); //not new Exception

12         if(array.length==0)

13             throw new ArrayIndexOutOfBoundsException("Array is empty"); //not new Exception

14         if(begin<0)

15             throw new ArrayIndexOutOfBoundsException("begin is less than 0"); //not new Exception

16         if(end<begin)

17             throw new ArrayIndexOutOfBoundsException("end is less than begin"); //not new Exception

18         //Missing this

19         if(end>array.length)

20             throw new Exception("end is larger than the length of array");

21         

22         //

23         while(end>begin){

24             int temp = array[begin];

25             array[begin]=array[end];

26             array[end]=temp;

27             

28             end--;

29             begin++;

30         }

31     }
  • 解法有很多,利用stack也可以,但交换的方法比较优雅
  • 参数的检验一定要到位。而且不要打印错误,要抛出异常。抛出的异常尽量精准,不要全抛出Exception
  • 进一步会考使用单元测试,提供测试用例

你可能感兴趣的:(数组)