zoukankan      html  css  js  c++  java
  • 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     }
  • 相关阅读:
    webstorm 自定义代码模板
    HTML5 manifest ApplicationCache
    WebStorm 快捷键收藏
    函数内巧用注释实现多行文本拼接
    图片剪裁上传插件
    将json转为复杂url参数
    CSS3实现半像素边框
    打造自己的3D全景漫游
    自适应rem布局
    header页头内容整理
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8481739.html
Copyright © 2011-2022 走看看