insert an element at index into array

Posted davidnyc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了insert an element at index into array相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

在angular中用node.js连接redis时遇到的问题——process is not defined at Object../node_modules/redis-errors/ind

在angular中用node.js连接redis时遇到的问题——process is not defined at Object../node_modules/redis-errors/ind

Print 'element' in list 返回一个 <Element 'element 1' at 0x0000013C6D4B9270>

每次调用 .insert() 或 .remove(at:) 时,在 UserDefaults 中保存更新的 Set

LF.366.Linked List Insert At Index

Search an Element in an array