Java Arrays array related algorithm questions, originated from Dachang and "Jianzhi offer", welcome to leave a message to add~~

Arrays provided in the Java language are used to store fixed-size elements of the same type.

Instead of directly declaring 100 independent variables number0, number1, ...., number99, you can declare an array variable like numbers[100]. Unlike the collection ArrayList, which can be dynamically expanded, the array is static, an array instance has a fixed size, and the type of the elements is the same. Once created, the capacity cannot be changed.

In order to facilitate learning, the editor has organized a list of algorithm topics related to arrays:


text

1. [Search] in a two-dimensional array

Topic description : In an n*m two-dimensional array, each row is sorted in ascending order from left to right, and each column is sorted in ascending order from top to bottom. Please complete an efficient function, input such a two-dimensional array and an integer, and determine whether the array contains the integer.

Problem- solving idea : Double pointer method, starting from the upper right corner of the array, if it is less than the target number, it goes down, and if it is greater than the target number, it goes to the left.

Example:

Input:
 [ [1, 4, 7, 11, 15],
    [2, 5, 8, 12, 19],
    [3, 6, 9, 16, 22],
    [10, 13, 14, 17, 24] ,
    [18, 21, 23, 26, 30] ]

Output: Given target =  5, return  true;given target =  20, return  false.

    public boolean findNumberIn2DArray(int[][] matrix, int target) {
        if (matrix == null || matrix.length == 0) return false;
        int row = 0;
        int col = matrix.length-1;
        while (row < matrix.length && col >= 0) {
            int temp = matrix[row][col];
            if (temp > target) {
                col--;
            } else if (temp < target){
                row++;
            } else {
                return true;
            }
        }
        return false;
    }

2. [Find] in a one-dimensional array

2.1 [Find out] more than [half] numbers in the array

Question Description : There is a number in the array that occurs more than half of the length of the array, please find the number. Arrays can be assumed to be non-empty and that a given array always has a majority of elements.

Problem- solving idea : sort first, more than half of the numbers will definitely cover the middle element, find it.

Example:

Input: [1, 2, 3, 2, 2, 2, 5, 4, 2]
Output: 2

    public int majorityElement(int[] nums) {
        Arrays.sort(nums);
        return nums[nums.length/2];
    }

2.2 [Find] the [repeated] numbers in the array

Title description : All numbers in an array nums of length n are in the range 0 to n-1. Some numbers in the array are repeated, but I don't know how many numbers are repeated, and I don't know how many times each number is repeated. Find any repeated number in the array.

Problem- solving idea : After sorting, compare two adjacent elements, and if they are equal, they are repeated elements.

Input: [2, 3, 1, 0, 2, 5, 3]
Output: 2 or 3


3. [Number of times the number appears]

3.1 Except for [one] number in the array, all other numbers appear [twice]

Question Description : In an array  , all numbers appear twicenums  except for a number that appears only once . Please find the number that occurs only once .

Problem- solving idea : Because the same XOR is 0, and the difference is 1, the XOR result of two identical numbers is 0, and the XOR result of all numbers must be the only number that appears once.

    public int singleNumber(int[] nums) {
        int num = nums[0];
        for (int i = 1; i < nums.length; i++) {
            num ^= nums[i];
        }
        return num;
    }

3.2 Except for [one] number in the array, all other numbers appear [ three times ]

Question Description : In an array  , all numbers appear three timesnums  , except for a number that appears only once . Please find the number that occurs only once .

Problem- solving idea : Use map to find the number that appears only once, and try it no matter how many times other numbers appear, but the space complexity is not O(1).

    public int singleNumber(int[] nums) {
        List<Integer> list1 = new ArrayList<Integer>();
        Map<Integer, Integer> map = new HashMap<>();
        for (int i : nums) {
            if (list1.contains(i)) {
                map.put(i, i);
            } else {
                list1.add(i);
            }
        }
        for (int j : list1) {
            if (!map.containsKey(j)) {
                return j;
            }
        }  
        return -1;
    }

3.3 Except for [two] numbers in the array, all other numbers appear [twice]

Question Description : In an array of integers  nums , all but two numbers appear twice . Please write a program to find these two numbers that appear only once. The time complexity is required to be O(n) and the space complexity is O(1).

Problem- solving idea : single-pointer method, sort first, then compare the two values ​​before and after, skip if they are equal, and output the previous target value if they are not equal.

    public int[] singleNumbers(int[] nums) {
        int[] ret = new int[2];
        Arrays.sort(nums);
        int i = 1, index = 0;
        while (i < nums.length) {
            // 与前一个相等就跳过,不等说明i-1是目标数
            if (nums[i] == nums[i-1]) {
                i += 2;
                // 处理目标数字在最后的情况
                if (i == nums.length) {
                    ret[index] = nums[i-1];
                }
            } else {
                ret[index++] = nums[i-1];
                i++;
            }  
        }
        return ret;
    }

3.4  [ First] character that appears [once]

Topic description : In an integer array  nums , there are multiple numbers that appear only once, find the first number that appears only once.

Problem- solving ideas : Use the orderliness of LinkedHashMap.

    public int FirstNotRepeatingChar(int[] arry) {
        LinkedHashMap<Integer, Integer> linkMap = new LinkedHashMap<>();
        for (int i = 0;i < arry.length;i++) {
            if (linkMap.containsKey(arry[i])) {
                linkMap.put(arry[i], linkMap.get(arry[i]) + 1);
            } else {
                linkMap.put(arry[i], 1);
            }
        }
        Iterator<Map.Entry<Integer, Integer>> it = linkMap.entrySet().iterator();
        while(it.hasNext()) {
            Map.Entry<Integer, Integer> temp = it.next();
            if (temp.getValue() == 1) {
                return temp.getKey();
            }
        }
        return -1;
    }

3.5  [First] Repeated characters

Topic description : There are multiple numbers in an integer array  nums that only appear multiple times, find the first repeated number.

Problem- solving idea : Using the non-repeatability of HashSet is more convenient and efficient than HashMap.

    public int findDuplicate(int[] numbers) {
        HashSet<Integer> set = new HashSet<>();
        for (int i : numbers) {
            if (set.contains(i)) {
                return i;
            }
            set.add(i);
        }
        return -1;
    }

4. [Merge] Two ordered arrays

Problem description : You are given two   integer array  sums  in non-decreasing order , and two integer sums   ,   each representing   the number of elements in the  sum  . Please  merge into   , so that the merged array is also in  non-decreasing order  .nums1 nums2mnnums1nums2 nums2 nums1

Problem- solving idea : Because it is an increasing order, consider entering the maximum value from the end, and then traverse in reverse order.

Example:

Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
Output: [1,2,2,3,5,6]
Explanation: Need to combine [1,2,3] and [2,5,6], the combined result is [1,2,2,3,5,6].

    public void merge(int[] nums1, int m, int[] nums2, int n) {
        int end = m+n-1;
        int i = m-1;
        int j = n-1;
        while (j >= 0) {
            if (i >= 0 && nums1[i] > nums2[j]) {
                nums1[end--] = nums1[i--];
            } else  {
                nums1[end--] = nums2[j--];
            }
        }
    }

5. Arrange the array into [the smallest number]

Question description : Input an array of non-negative integers, concatenate all the numbers in the array into a number, and print the smallest one of all the numbers that can be concatenated.

Problem-solving idea : rewrite the sorting rules, note: you cannot use Array.sort() to sort, otherwise 3 will be in front of 30, obviously 330>303 is not suitable.

    public String minNumber(int[] nums) {
        if (nums == null || nums.length == 0) return "";
        // 冒泡排序的原理
        for (int i=0;i<nums.length;i++) {
            for (int j=i+1;j<nums.length;j++) {
                if (this.compare(nums[i], nums[j])) {
                    int temp = nums[j];
                    nums[j] = nums[i];
                    nums[i] = temp;
                }
            }
        }
        // 遍历输出结果
        StringBuilder sb = new StringBuilder("");
        for (int i=0;i<nums.length;i++) {
            sb.append(nums[i]+"");
        }
        return sb.toString();
    }
    // 重写比较规则(compare方法拆出来是为了更直观)
    private boolean compare (int a, int b) {
        Long left = Long.valueOf(a + "" + b);
        Long right = Long.valueOf(b + "" + a);
        if (left > right) {
            return true; 
        } else {
            return false; 
        }
    }

6. [Brackets] matching problem

Question Description: Given a string containing only  '(' sums  ')' , find the length of the longest valid (well-formed and contiguous) parenthesized substring.

Idea: Take advantage of the characteristics of the stack to pad an additional number at the bottom of the stack to store the value.

Example:

Input: s = ")()())"
Output: 4
Explanation: The longest valid parenthesized substring is "()()"

    public int longestValidParentheses(String s) {
        int maxNum = 0;
        Stack<Integer> stack = new Stack<Integer>();
        stack.push(-1);

        // 栈里:有多少'(',就需要多少')'
        // 栈底存储上一次满足匹配位置的元素下标,用于计算长度
        for (int i = 0;i < s.length();i++) {
            if (s.charAt(i) == '(') {
                stack.push(i);
            } else {
                stack.pop();
                if (stack.isEmpty()) {
                    stack.push(i);
                } else {
                    // 下标在这里用来计算匹配长度
                    maxNum = Math.max(maxNum, i-stack.peek());
                }
            }
        }
        return maxNum;
    }

7. Find the longest [Palindromic Substring] #

Topic description: Given a string s, find the longest palindrome substring in s, assuming that the maximum length of s does not exceed 1000. tips:  palindrome string: both forward and reverse reading are the same.

Ideas: The idea of ​​dynamic programming, other methods are welcome to view the following blog posts.

Example:

Input: s = "babad"
Output: "bab"
Explanation: "aba" is also the answer that matches the meaning of the question.

    public String longestPalindrome(String s) {
        if (s.isEmpty()) return s;
        int len = s.length();
        boolean[][] dp = new boolean[len][len];
        int left = 0, right = 0;
        // 倒序向前遍历
        for (int i = len - 2; i >= 0; i--) {
            for (int j = i + 1; j < len; j++) {
                // 小于3一定是回文,aa或aba
                dp[i][j] = s.charAt(i) == s.charAt(j) && ( j-i < 3 || dp[i+1][j-1]);
                // 更新左右边界
                if(dp[i][j] && right-left < j-i){
                    left = i;
                    right = j;
                }
            }
        }
        return s.substring(left,right+1);
    }

LeetCode[5] - Find the longest palindrome substring && dynamic programming && recursion && violent enumeration


8. [Maximum Sum] of consecutive subarrays #

Topic description: Input an integer array, there are positive numbers and negative numbers in the array, one or several consecutive integers in the array form a sub-array, and find the maximum sum of consecutive sub-arrays.

Idea: Dynamic programming, if the sum is less than 0, the maximum sum is set to the current value, otherwise the maximum sum is calculated.

    public int maxSubArray(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int sum = nums[0];
        int result = nums[0];
        for (int num : nums) {
            // 如果 sum + num < num,说明前面的计算结果 sum 没有意义,所以要换掉
            sum = sum > 0 ? sum + num : num;
            // result永远保存最大值 
            result = Math.max(sum, result);
        }
        return result;
    }

9. Put the [odd number] in the array before the [even number] #

Topic description : Input an integer array, implement a function to adjust the order of the numbers in the array, so that all odd numbers are in the first half of the array, all even numbers are in the second half of the array, and ensure odd and odd, even and even numbers The relative position between them remains unchanged. Requirements: time complexity O(n), space complexity O(1)

Problem- solving ideas : The principle of bubbling, when an even number is encountered, it will bubble to the end .

    public void reOrderArray_2(int[] array) {
        if (array == null || array.length == 0) return;
        int i = 0, index = 0;
        int len = array.length - 1;
        while(i < len - index){
            if (array[i] % 2 == 0) {
                for (int j = i; j < array.length - 1;j++) {
                    int temp = array[j];
                    array[j] = array[j+1];
                    array[j+1] = temp;
                }
                index ++;
            }
            i++;
        }
    }

10. The [coincident] and [not coincident] parts of the two arrays

Topic description : Country A and Country B are at war, and their goal is n pieces of land. Country A wants to get p pieces of land among the n pieces of land, and country B wants to get q pieces of land among the n pieces of land. You need to calculate, how many pieces of land are wanted by only country A, how many pieces of land are wanted by only country B, and how many pieces of land are wanted by both countries.

Problem- solving idea : sort first, and then take the same part by double pointer method.

    public int[] samedrome(int[] country_a, int[] country_b){
        int[] result = new int[3];
        Arrays.sort(country_a);
        Arrays.sort(country_b);

        // i是A指针,j是B指针,index是重合部分的长度
        int i=0, j=0, index=0;
        while (i < country_a.length && j < country_b.length) {
            if (country_a[i] > country_b[j]) {
                j++;
            } else if (country_a[i] < country_b[j]) {
                i++;
            } else {
                i++;
                j++;
                index++;
            }
        }
        result[0] = country_a.length - index;  // a
        result[1] = country_b.length - index;  // b
        result[2] = index;  // 重合
        return result;
    }

11. Find two numbers with the smallest product

Topic description : Input an array of [increasing sorting] and a number S, find two numbers in the array so that their sum is exactly S, if the sum of multiple pairs of numbers is equal to S, output the smallest product of the two numbers .

Problem- solving idea : Define two pointers, traversing from the front and the back respectively. The farther the interval is, the smaller the product, so the first two numbers have the smallest product.

    public ArrayList<Integer> FindNumbersWithSum(int [] array, int sum) {
        ArrayList<Integer> retList = new ArrayList<>();
        if (array == null ) return retList;
        int left = 0;
        int right = array.length - 1;
        while (left < right) {
            int temp = array[left] + array[right];
            if (temp == sum){
                retList.add(array[left]);
                retList.add(array[right]);
                break;
            } else if (temp < sum) {
                left++;
            } else {
                right--;
            }
        }
        return retList;
    }
       

Guess you like

Origin blog.csdn.net/weixin_44259720/article/details/123279873