Algorithmic customs clearance village - not simple addition, deletion, modification and query of arrays

1. Adding elements to an ordered array

First find the position of the element to be inserted, then move the position including the following elements back one bit, and then insert the element into the array. First, you need to judge whether the current array can continue to add elements.

    /**
     * 插入指定位置元素
     *
     * @param arr     有序数组
     * @param size    已经存储的元素数量,从1开始
     * @param element 插入的元素
     * @return
     */
    public static int addByElement(int[] arr, int size, int element) {
    
    
        // size从1开始表示实际个数,arr.length也是从1开始
        if (size >= arr.length) {
    
    
            return -1;
        }
        // 防止插入的数大于当前最大值
        int index = size;
        for (int i = 0; i < size; i++) {
    
    
            if (element < arr[i]) {
    
    
                index = i;
                break;
            }
        }
        // j开始元素都后移
        for (int j = size; j > index; j--) {
    
    
            arr[j] = arr[j - 1];
        }
        // 插入元素
        arr[index] = element;
        return index;
    }

2. Delete the specified position element

First find the position where the deleted element exists. If the position exists, record it, and then judge whether the subscript of this position is -1. If it is not -1, it means that it exists, and then move all the elements behind the deleted element forward.

  /**
     * 删除元素key
     *
     * @param arr  数组
     * @param size 数组元素个数从1开始
     * @param key  删除元素
     * @return
     */
    public static int removeByElement(int[] arr, int size, int key) {
    
    
        if (size >= arr.length) {
    
    
            return -1;
        }
        // index是-1,表示不存在
        int index = -1;
        for (int i = 0; i < size; i++) {
    
    
            if (arr[i] == key) {
    
    
                index = key;
                break;
            }
        }
        if (index != -1) {
    
    
            for (int i = index + 1; i < size; i++) {
    
    
                arr[i - 1] = arr[i];
                size--;
            }
        }
        return size;
    }

3. Monotonic series

Monotonic Arrays
An array is monotonic if it is monotonically increasing or monotonically decreasing.
The array nums is monotonically increasing if nums[i] <= nums[j] for all i <= j. The array nums is monotonically decreasing if nums[i] >= nums[j] for all i <= j.
Returns true if the given array nums is monotonic, false otherwise.

3.1 Analysis

Since the topic contains increment and decrement, it is impossible to know whether it is increment or decrement by direct judgment, so two variables inc and desc need to be used to record. If the elements are all increment, then the final use of inc||desc will only be true. Once fasle shows, not monotonous.

    public boolean isMonotonic(int[] nums) {
    
    
    	// 递增标志
        boolean inc = true;
        // 递减标志
        boolean desc = true;
        for(int i=0;i<nums.length-1;i++){
    
    
            if(nums[i]>nums[i+1]){
    
    
            // 由于是递减的,所以递增的不满足,设置为false
                inc = false;
            }
			// 同理
            if(nums[i] < nums[i+1]){
    
    
                desc = false;
            }
        }
		// 只要一个为true就是true,如果都是false那么就不是递增的
        return inc || desc;
    }

4. Search insertion position

Search insertion position
Given a sorted array and a target value, find the target value in the array and return its index. If the target value does not exist in the array, returns the position where it will be inserted in order.
Please use an algorithm with time complexity O(log n).

4.1 Analysis

The topic requires the time complexity of logn, and I think of two points at the first time.

   public int searchInsert(int[] nums, int target) {
    
    
        int n = nums.length;
        int left =0;
        int right = n-1;
        int ans = n;
        while(left<=right){
    
    
        // 这里要加上相应的括号,否则优先级会报错
            int mid = ((right-left) >>1) +left;
            if(target<=nums[mid]){
    
    
                ans = mid;
                right = mid-1;
            }else{
    
    
                left = mid+1;
            }
        }
        return ans;
    }

5. Merge two sorted arrays

Merging Two Sorted Arrays
Given you are given two integer arrays nums1 and nums2 in non-decreasing order, and two integers m and n denoting the number of elements in nums1 and nums2 respectively.
Please merge nums2 into nums1 so that the merged array is also arranged in non-decreasing order.
Note: Ultimately, the merged array should not be returned by the function, but stored in the array nums1. To cope with this situation, the initial length of nums1 is m + n, where the first m elements represent elements that should be merged, and the last n elements are 0 and should be ignored. nums2 has length n.

5.1 Analysis

5.1.1 First add all elements to nums1, and then sort nums1.

 public void merge(int[] nums1, int m, int[] nums2, int n) {
    
    
      for(int i=0;i<nums2.length;i++){
    
    
          nums1[m+i] = nums2[i];
      }      
      Arrays.sort(nums1);
    }

insert image description here
But obviously the efficiency is not high. The first time traversing nums2, the time complexity is O(n), the second time using Arrays sorting, the bottom layer is quick sort, the time complexity is O(nlogn)

5.2.2 Since the two arrays are in order, it is only necessary to compare the last elements of the two arrays, put the larger one at the end of nums1, and finally put the unfinished elements into nums1.

    public static void merge(int[] nums1, int m, int[] nums2, int n) {
    
    
        // 合并索引位置
        int i = m + n - 1;
        // nums1的最后一个元素
        int len1 = m - 1;
        // nums2的最后一个元素
        int len2 = n - 1;
        while (len1 >= 0 && len2 >= 0) {
    
    
            if (nums1[len1] <= nums2[len2]) {
    
    
                // 将最大的元素放入nums1的末尾
                nums1[i--] = nums2[len2--];
            } else {
    
    
                nums1[i--] = nums1[len1--];
            }
        }
        // 判断剩余数组是否有空余元素
        while (len2 != -1) nums1[i--] = nums2[len2--];
        while (len1 != -1) nums1[i--] = nums1[len1--];
    }

insert image description here
The time complexity here is the length of the two arrays of O(m+n). It can be seen that the efficiency is still very high,

Summarize

The difficulty of the array problem lies in how to choose a relatively reasonable way to solve the problem, especially the addition of elements in the array, and the movement of deleting elements requires special attention.

Guess you like

Origin blog.csdn.net/qq_52843958/article/details/131899516