• 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     }
  • 相关阅读:
    ios 封装sqllite3接口
    ios7与ios6UI风格区别
    C/C++面试题
    单链表反转
    字符串倒序输出
    简单选择排序
    插入排序
    冒泡
    快速排序
    C++ new delete(二)
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8481739.html
Copyright © 2020-2023  润新知