given an array, and an element to insert, and the position to insert this element,return a new array with the element inserted 1,2,3,4,5,6 -> 1,2,3,15,4,5,6
1 public static void main(String[] args) { 2 int[] org = new int[]{1,2,3,4,5,6} ; 3 int[] res = insert(org, 15, 3); 4 print(res); 5 } 6 7 private static int[] insert(int[] org, int val, int insertIndex ) { 8 //note the way to create array: [# of items] = length; the last index = length - 1 9 int[] res = new int[org.length+1] ; 10 //find the ending index: anything <= remain the same 11 int pos = Math.min(insertIndex, org.length) ; //3 12 //[1,2,3] remain the same 13 for (int i = 0; i < pos ; i++) { 14 res[i] = org[i] ; 15 } 16 //create the new item 17 res[pos] = val ; 18 //the rest remain the same 19 for (int indexOld = pos; indexOld < org.length; indexOld++) { 20 res[indexOld+1] = org[indexOld] ; 21 } 22 /* the following is wrong: will jump one item 23 for (int i = pos+1; i < org.length ; i++) { 24 res[i] = org[i]; 25 } 26 * */ 27 return res ; 28 } 29 private static void print(int[] arr){ 30 for (int i = 0; i <arr.length ; i++) { 31 System.out.println(arr[i]); 32 } 33 }
原文地址:https://www.cnblogs.com/davidnyc/p/8481739.html
时间: 2024-11-09 02:08:34