码迷,mamicode.com
首页 > 其他好文 > 详细

insert an element at index into array

时间:2018-02-28 10:34:09      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:one   oid   gpo   str   into   res   out   []   find   

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     }

 

insert an element at index into array

标签:one   oid   gpo   str   into   res   out   []   find   

原文地址:https://www.cnblogs.com/davidnyc/p/8481739.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!