Seven days to brush your finger

Time:2020-10-26

27. Arrangement of strings

1. Title Description

Enter a string and print all permutations of characters in the string in dictionary order.

2. Examples

For example, if the string ABC is input, all the strings ABC, ACB, BAC, BCA, cab and CBA that can be arranged by the characters a, B, C are printed.

Enter a string no more than 9 in length (there may be repeated characters), and the characters include only upper and lower case letters.

3. Problem solving ideas

Using the recursive method, the problem is converted to fix the first character and find the arrangement of the remaining characters, which is the same as the original problem.

Recursive algorithm implementation:

Seven days to brush your finger

(1) Traverse all the characters that may appear in the first position (i.e. exchange the first character with all the following characters in turn);

(2) Fix the first character and find the arrangement of the following characters (i.e. in the traversal process of step 1, insert recursion for Implementation).

Take “ABC” as an example

In this case, I call it the initial state [‘c ‘], i.e. the first state is called [‘c’]

Then J = 0, swap (CH, 0, 0), is [‘a ‘,’b’,’c ‘], enters recursion, adjusts itself, but I is 1, and the state after exchanging (0,0) position is called state B

I is not equal to 2. When I come here, j = 1, I execute the first swap (CH, 1, 1). In this state, I call it state C1, and then enter the recursive function. At this time, it is marked as T1, and I is 2. Then I will enter the previous if and put “ABC” in the list

——-In this case, the result set is [“ABC”]

2. Completion of execution list.add After that, when return is encountered, it will return to T1. Next, execute the second swap (CH, 1, 1), and state C1 will return to state B

After recovery, continue to execute the for loop. At this point, j = 2, then swap (CH, 1, 2) to get “ACB”. This state is called C2, and then the recursive function is executed. At this time, it is marked as T2, and I + 1 = 2 is found. Therefore, it is also added to the result set. At this time, the return is returned to T2 and executed downward

——-In this case, the result set is [“ABC”, “ACB”]

Then execute the second swap (CH, 1, 2), state C2 returns to state B, and then the for loop of state B exits to return to state a

//A|b|c (state a)

// |

// |swap(0,0)

// |

//A|b|c (state B)

// /

//Swap (1,1) / swap (1,2) (state C1 and state C2)

// /

// a|b|c a|c|b

3. After returning to state a, continue the for loop, j = 1, that is, swap (CH, 0, 1), that is, “BAC”. This state can be called state a again. The following steps are the same as above

——-In this case, the result set is [“ABC”, “ACB”, “BAC”, “BCA”]

//A|b|c (state a)

// |

// |swap(0,1)

// |

//B|a|c (state B)

// /

//Swap (1,1) / swap (1,2) (state C1 and state C2)

// /

// b|a|c b|c|a

4. Continue with the for loop, j = 2, that is, swap (CH, 0, 2), that is, “cab”. This state can be called state a again, and the following steps are the same as above

——-In this case, the result set is [“ABC”, “ACB”, “BAC”, “BCA”, “cab”, “CBA”]

//A | b| C (state a)

// |

// |swap(0,2)

// |

//C|b|a (state B)

// /

//Swap (1,1) / swap (1,2) (state C1 and state C2)

// /

// c|b|a c|a|b

5. Exit the for loop and end.

4. Java implementation

import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
public class Solution {
    public ArrayList<String> Permutation(String str) {
        List<String> list = new ArrayList();
        if (str.length() == 0) return (ArrayList)list;
        
        permutationHelper( str.toCharArray (), 0, list); // recursive implementation
        Collections.sort(list);
        return (ArrayList)list;
    }
    
    private void permutationHelper(char[] cs, int i, List<String> list){
        if (i ==  cs.length -1) {// if the index is the last digit
            String s = String.valueOf(cs);
            if (! list.contains (s) ) {// prevents duplicate strings, such as when entering AAB
                list.add(s);
                return;
            }
        }else{
            for (int j = i; j < cs.length; j++){
                swap(cs, i, j);
                permutationHelper(cs, i+1, list);
                Swap (CS, I, J); // backtracking method to recover the previous string order, so that the first bit can be exchanged with other bits in turn
            }
        }
    }
    
    Private void swap (char [] CS, int i, int j) {// swap two characters
        char temp;  
        temp = cs[i];
        cs[i] = cs[j];
        cs[j] = temp;
    }
}

5. Python implementation

# -*- coding:utf-8 -*-
class Solution:
    def Permutation(self, ss):
        # write code here
        if not ss:
            return []
        if len(ss) == 1:
            return ss 
 
        ssList = list(ss)
        ssList.sort () ා converts a string to a list and sorts it
        ret = []
        For I in range (len (sslist)):
            If I > 0 and sslist [i] = = sslist [I-1]:
                continue 
            temp = self.Permutation(''.join(ssList[: i]) + ''.join(ssList[i+1: ]))
            for j in temp:
                ret.append(ssList[i] + j)
 
        return ret

28. Numbers in the array that appear more than half the time

1. Title Description

There is a number in the array that appears more than half the length of the array. Please find this number.

2. Examples

For example, enter an array of length 9 {1,2,3,2,2,2,5,4,2}. Since the number 2 appears in the array five times, more than half the length of the array, output 2. If not, 0 is output.

3. Problem solving ideas

Use hash table idea: use hash, key is number, value is the number of times

4. Java implementation

import java.util.Map;
import java.util.HashMap;

public class Solution {
    public int MoreThanHalfNum_Solution(int [] array) {
        if (array.length == 0) return 0;
        HashMap<Integer, Integer> map = new HashMap();
        for (int i = 0; i < array.length; i++){
            int num = array[i];
            if ( map.containsKey (Num)) {// if the key value in the original map exists, then + 1
                map.put(num, map.get(num)+1);
            }else{
                map.put(num, 1);
            }
        }
        for ( Map.Entry <Integer, Integer> entry:  map.entrySet ()) {// traverses all indexes and values
            if (entry.getValue() > array.length/2){
                return entry.getKey();
            }
        }
        return 0;
    }
}

5. Python implementation

# -*- coding:utf-8 -*-
class Solution:
    def MoreThanHalfNum_Solution(self, numbers):
        # write code here
        #Use hash table
        if not numbers:
            return 0
 
        hashes = {}
        length = len(numbers)
        for num in numbers:
            If hashes.get (Num): if num exists in the dictionary
                hashes[num] += 1
            else:
                hashes[num] = 1
            if hashes[num] > (length // 2):
                return num 
        return 0

29. The minimum number of K

1. Title Description

Enter n integers to find the smallest K.

2. Examples

For example, 1, 2, 8, 4, 1, 2, 4, 3, 4, 3, 4, 4, 3, 4, 4, 3, 4, 3, 4, 4, 3, 4, 3, 4, 4, 3, 4, 3, 4, 4, 3, 4, 3, 4, 4, 3, 4, 3, 4, 4, 4, 3, 4, 4,.

3. Problem solving ideas

Note: find the minimum n values, use the maximum heap to find the largest n values, and use the minimum heap

Using heap sorting, O (n logK), it is suitable for processing massive data

(1) Traversing the input array, insert the first k numbers into the heap;

(2) Continue to read in the element from the input array as the integer to be inserted, and compare it with the maximum value in the heap: if the value to be inserted is smaller than the current maximum value, replace the existing maximum value with this number; if the value to be inserted is larger than the current maximum value, discard this number and continue to read the next number.

In this way, the K number in the heap is dynamically maintained to ensure that it only stores the smallest number of the first k in the input array, and finally outputs the heap.

4. Java implementation

In Java, the priority queue is used as the heap, and the maximum value is returned each time, so the maximum heap is used;

import java.util.Queue;
import java.util.PriorityQueue;
import java.util.Collections;
import java.util.ArrayList;

public class Solution {
    public ArrayList<Integer> GetLeastNumbers_Solution(int [] input, int k) {
        ArrayList<Integer> res = new ArrayList();
        int size = input.length;
        if (size == 0 || size < k || k <= 0) return res;
        Queue<Integer> q = new PriorityQueue(k,  Collections.reverseOrder ()); // maximum heap
        
        for (int i = 0; i < size; i++){
            If (I + 1 < = k) {// if there are not enough K values, it will be put into the maximum heap, and the maximum heap will be sorted automatically
                q.add(input[i]);
            }else{
                If (input [i] < q.peek()) {// if the maximum value in the maximum heap is less than the value of the array, delete the maximum value
                    q.poll();
                    q.add(input[i]);
                }
            }
        }
        while(!q.isEmpty()){
            res.add(q.poll());
        }
        return res;
    }
}

5. Python implementation

# -*- coding:utf-8 -*-
class Solution:
    def GetLeastNumbers_Solution(self, tinput, k):
        # write code here
        import heapq 
        length = len(tinput)
        if not tinput or length < k or k <= 0:
            return []
        if length == k:
            tinput.sort()
            return tinput
        
        output = []
        for num in tinput:
            if len(output) < k:
                output.append(num)
            else:
                output = heapq.nlargest(k, output)
                
                if output[0] < num:
                    continue 
                else:
                    output[0] = num 
                
        return output[::-1] 

If you find this article useful, please click “like”

30. Maximum sum of continuous arrays

1. Title Description

Hz will occasionally take some professional questions to deceive those non computer majors. Today, after the test group held a meeting, he said again: in the old one-dimensional pattern recognition, it is often necessary to calculate the maximum sum of continuous sub vectors. When the vectors are all positive numbers, the problem is solved very well. But if a vector contains a negative number, should it contain a negative number and expect a positive number next to it to make up for it?

2. Examples

For example: {6, – 3, – 2,7, – 15,1,2,2}, the maximum sum of continuous sub vectors is 8 (from the 0 th to the 3rd). Give an array and return the sum of its largest consecutive subsequence. Will you be fooled by it? (the length of the sub vector is at least 1)

3. Problem solving ideas

Using dynamic programming

F (I): take array [i] as the maximum value of the sum of the subarray of the end elements, and the relative position of the elements of the subarray remains unchanged

F(i)=max(F(i-1)+array[i] , array[i])

Res: the maximum value of the sum of all subarrays

res=max(res,F(i))

For example, the array [6, – 3, – 2, 7, – 15, 1, 2, 2]

Initial state:

F(0)=6

res=6

i=1:

F(1)=max(F(0)-3,-3)=max(6-3,3)=3

res=max(F(1),res)=max(3,6)=6

i=2:

F(2)=max(F(1)-2,-2)=max(3-2,-2)=1

res=max(F(2),res)=max(1,6)=6

i=3:

F(3)=max(F(2)+7,7)=max(1+7,7)=8

res=max(F(2),res)=max(8,6)=8

i=4:

F(4)=max(F(3)-15,-15)=max(8-15,-15)=-7

res=max(F(4),res)=max(-7,8)=8

and so on

The final value of res is 8

4. Java implementation

public class Solution {
    public int FindGreatestSumOfSubArray(int[] array) {
        int res = array[0];
        int maxValue = array[0];
        
        for (int i = 1; i < array.length; i++){
            maxValue = Math.max(array[i], array[i] + maxValue);
            res = Math.max(res, maxValue);
        }
        return res;
    }
} 

5. Python implementation

# -*- coding:utf-8 -*-
class Solution:
    def FindGreatestSumOfSubArray(self, array):
        # write code here
        if not array:
            return 
        ret = float('-inf')
        cur = 0
        for num in array:
            If cur < = 0: # if all the previous values are negative, discard the previous values
                cur = num 
            else:
                cur += num 
            RET = max (RET, cur) ා save and update the maximum value
        return ret

If you find this article useful, please click “like”

31 the number of occurrences of integer 1

1. Title Description

Find the number of times 1 appears in integers 1 ~ 13, and calculate the number of times 1 appears in integers 100 ~ 1300?

2. Examples

For this reason, he specially counted the number of 1 in 1 ~ 13, including 1, 10, 11, 12 and 13, so there were 6 times in total, but he had no idea about the latter problem. Acmer hopes that you can help him and generalize the problem. You can quickly find the number of times 1 appears in any nonnegative integer interval (from 1 to the number of times 1 appears in n).

3. Problem solving ideas

Method 1: the method of finding the law: we take 345 as an example to find the law

2. The rule of 1 in 1 bit: 1

Seven days to brush your finger

The number of times a bit 1 is required to appear is undoubtedly related to the number at the top of a hundred and a thousand.

Calculating the number of times a single bit appears in M, it can be seen that K (single digit) is greater than 1, so there must be 1,

The first case: k > 0

So there are: 001011021… 101,。。 341 【Note: the number of other bits is not considered at this time

35 times from 00 to 34.That is prenum + 1

The second case: k = = 0: [i.e. if M = 340]

We know that there must be no 1 in 340 bits, but there will be one bit in 0-339 bits. Therefore, calculating the number of 1 in 339 bits is equivalent to the number of 340

So there are: 001011021… Three hundred and thirty-one

34 times from 00 to 33,Prenum

Summary:
Set the occurrence times of bits as: count
If k > 0, count = prenum + 1;
If k = 0, count = prenum;

2

Seven days to brush your finger

The first case: k > 1

The situation is: 01x, 11x, 21x, 31x, where x bits will appear 10 times, that is, 0-9, 4 times 10 is 40

There were 40 times from 0 to 3.That is (prenum + 1) * base

The second case: k = = 0 [if M = 305]

The same as the single digit rule, we can also equate 305 to 295, then K is not 0, so we can apply the rule of k > 1

So the number of times it appears is: 01x, 11x, 21x, in which X bits will appear 10 times. 3 times 10 is 30,Prenum * base

The third case: k = = 1 [if M = 315]

In this case, it is related to the single digit value,

We know that when m = 305, the number of times that the ten digit appears 1 is 30 times

306-309 ten did not appear, 1310-315 appeared six times.

So 30 + 6 timesThat is prenum * base + tail + 1

Summary:
Set the occurrence times of bits as: count
If k > 1, count = (prenum + 1) * base;
If k = = 0, count = prenum * base;
If k = = 1, count = prenum * base + tail + 1;

2.3 the rule of ten can be extended to hundreds and thousands

example:

  • 534 = (number of occurrences of bit 1) + (frequency of occurrence of digit 1) + (frequency of occurrence of digit 1)

=(53_1+1)+(5_10+10)+(0*100+100)= 214

Why is the frequency of occurrence of 100 digit 1? [100101, – 199] 100 times

  • 530 = (53 1)+(5 10+10)+(0*100+100) = 213
  • 504 = (50 1+1)+(5 10)+(0*100+100) = 201
  • 514 = (51 1+1)+(5 10+4+1)+(0*100+100) = 207
  • 10 = (1 1)+(010+0+1) = 2

The second method: using violence to solve the problem

Save all 0-n values to StringBuffer, and then traverse it. If it is equal to the character ‘1’, count + 1;

4. Java implementation

The first method is to find the law

public class Solution {
    public int NumberOf1Between1AndN_Solution(int n) {
    
        int count = 0, base = 1;
        int round = n;  
        while (round > 0){
            Int k = round% 10; // get
            round /= 10;
            count += round * base;
            if (k == 1){
                Count + = (n% base) + 1; // N save it to calculate the value of tail
            }else if (k > 1){
                count += base;
            }
            Base * = 10; // update the value of base, and calculate the value of tens, hundreds and thousands
        }
        return count;
    }
    
}

The second method: using violence to solve the problem

public class Solution {
    public int NumberOf1Between1AndN_Solution(int n) {
        //Direct use of violence solution:
        StringBuffer sb = new StringBuffer();
        for (int i = 1; i<= n; i++){
            sb.append(i);
        }
        
        String str = sb.toString();
        int count = 0;
        for (int i = 0; i< str.length(); i++){
            if (str.charAt(i) == '1') count++;
        }
        
        return count;
    
    }
}

5. Python implementation

Violence solving method

# -*- coding:utf-8 -*-
class Solution:
    def NumberOf1Between1AndN_Solution(self, n):
        # write code here
        #Converts a number to a string
        count = 0
        for i in range(1, n+1):
            for s in str(i):
                if s == '1':
                    count += 1
        return count

If you find this article useful, please click “like”

32 – make the array the smallest

1. Title Description

Input an array of positive integers, put all the numbers in the array together into a number, print the smallest of all the numbers that can be spliced.

2. Examples

For example, if the array {3, 32321} is input, the minimum number that the three numbers can be arranged is 321323.

3. Problem solving ideas

Here, we define a function to compare the size of two strings S1 and S2. When comparing the sizes of S1 and S2, we first splice them together and compare the size of S1 + S2 and S2 + S1. If S1 + S2 is large, then S2 should be put in front. Therefore, according to this rule, S2 should be placed before S1. (similar to sorting algorithm)

For example: S1 = 32, S2 = 321, first convert the two strings into numbers, and compare the size of S1 + S2 = 32321 and S2 + S1 = 32132,

If the former is larger, switch S1 and S2.

The code uses a little trick here:

int pre = Integer.valueOf(numbers[i] +"" + numbers[j]); 
//Convert numbers to strings, concatenate, and convert to numbers

4. Java implementation

import java.util.ArrayList;

public class Solution {
    public String PrintMinNumber(int [] numbers) {
        
        String res = "";
        for (int i = 0; i < numbers.length; i++){
            for (int j = i+1; j < numbers.length; j++){
                int pre =  Integer.valueOf (numbers [i] + "+ numbers [J]); // convert numbers to strings, concatenate them, and then convert them to numbers
                int tail = Integer.valueOf(numbers[j] +"" + numbers[i]);
                if (pre > tail){
                    int temp;
                    temp = numbers[i];
                    numbers[i] = numbers[j];
                    numbers[j] = temp;
                }
            }
        }
        for (int i = 0; i < numbers.length; i++){
            res += numbers[i];
        }
        return res;

    }
}

5. Python implementation

# -*- coding:utf-8 -*-
class Solution:
    def PrintMinNumber(self, numbers):
        # write code here
        if not numbers:
            return ''
        strNum = [str(num) for num in numbers]
        
        for i in range(len(numbers)-1):
            for j in range(i+1, len(numbers)):
                if strNum[i]+strNum[j] > strNum[j]+strNum[i]:
                    strNum[i], strNum[j] = strNum[j], strNum[i]
                    
        return ''.join(strNum) 

If you find this article useful, please click “like”

33 ugly number

1. Title Description

Definition of ugly number: the number containing only prime factors 2, 3 and 5 is called ugly number.

2. Examples

For example, 6 and 8 are ugly numbers, but 14 is not, because it contains a prime factor of 7. We used to think of 1 as the first ugly number. Find the nth ugly number in the order from small to large.

3. Problem solving ideas

First of all, from the definition of ugly number, we know that the factor of an ugly number is only 2,3,5, then the ugly number P = 2 ^ X 3 ^ y 5 ^ Z, in other words, an ugly number must be obtained by multiplying another ugly number by 2, 3, or 5, then we can get 2,3,5 three ugly numbers by multiplying 2,3,5 from 1, and then we can get 4,6,10,6,9,15,10,15,25 by multiplying the three ugly numbers by 2,3,5. We found that this method can obtain repeated ugly numbers, and our title requires the nth ugly number.

(1) Ugly number array: 1

Queue multiplied by 2: 2

Queue multiplied by 3: 3

Queue multiplied by 5: 5

Select the minimum number 2 of the three queue heads to join the ugly number array, and multiply the minimum number by 2, 3, 5 to put into the three queues;

(2) Ugly number array: 1,2

Queue multiplied by 2: 4

Multiply the queue by three: three, six

A queue multiplied by five: five, ten

At this point, it may appear that the value multiplied by 5 is greater than the value multiplied by 3, so take the minimum value of multiplying by 3 and multiplying by 5

Select the minimum number 3 of the three queue heads to join the ugly number array, and multiply the minimum number by 2, 3, 5 to put it into the three queues;

(3) Ugly number array: 1,2,3

The queue multiplied by 2: 4, 6

The queue multiplied by 3: 6, 9

The queue multiplied by 5: 5, 10, 15

Select the smallest number 4 in the three queue heads and add it to the ugly number array. At the same time, multiply the minimum number by 2,3,5 and put it into the three queues;

4. Java implementation

import java.util.ArrayList;

public class Solution {
    public int GetUglyNumber_Solution(int index) {
        
        if (index <= 0) return 0;
        ArrayList<Integer> res = new ArrayList();
        res.add(1);
        int i2=0, i3=0, i5=0;
        
        while (res.size() < index){
            int i2_value = res.get(i2) * 2;
            int i3_value = res.get(i3) * 3;
            int i5_value = res.get(i5) * 5;
            //Find the minimum value
            int minValue = Math.min(i2_value, Math.min(i3_value, i5_value));
            res.add(minValue);
            if (i2_ Value = = minValue) I2 + +; // move index back
            if (i3_value == minValue) i3++;
            if (i5_value == minValue) i5++;
        }
        
        return res.get(res.size()-1);
    }
}

5. Python implementation

# -*- coding:utf-8 -*-
class Solution:
    def GetUglyNumber_Solution(self, index):
        # write code here
        If not index: ා if the index is 0, 0 is returned
            return 0 
        
        uglyNumbers = [1] * index
        
        index2, index3, index5 = 0, 0, 0
        nextIndex = 1
        while nextIndex < index: 
            minVal = min(uglyNumbers[index2] * 2, uglyNumbers[index3]*3, uglyNumbers[index5]*5)
            uglyNumbers[nextIndex] = minVal 
            
            While uglynumbers [index2] * 2 < = minval: # if it is less than the minimum value, move forward
                index2 += 1
            while uglyNumbers[index3] * 3 <= minVal:
                index3 += 1
            while uglyNumbers[index5] * 5 <= minVal:
                index5 += 1
                
            nextIndex += 1
        return uglyNumbers[-1]

If you find this article useful, please click “like”

34 – characters that appear only once at the first time

1. Title Description

Find the first character that appears only once in a string (0 < = string length < = 10000, all composed of letters), and return its position. If not, return – 1 (case sensitive)

2. Examples

nothing

3. Problem solving ideas

The first method: hash table method

Use hash to solve the problem, traverse the string, hash key value is the single character of traversal, value is the number of occurrences; finally, re traverse to find the key value with value 1 at the beginning

The second method: array method

Another more ingenious method: mainly hash, using the ASCII code of each letter as hash as the index of array. First, an array of 58 is used to store the number of times each letter appears. Why 58? This is mainly because the ASCII code corresponding to A-Z is 65-90, and the value of ASCII code corresponding to A-Z is 97-122, and the index of each letter is int (word) – 65, such as g = 103-65 = 38. The specific content recorded in the array is the number of times the letter appears. Finally, traverse the string to find out the first array A letter of 1 is enough, and the time complexity is O (n)

4. Java implementation

The first method: hash

import java.util.HashMap;

public class Solution {
    public int FirstNotRepeatingChar(String str) {
        int size = str.length();
        if (size == 0) return -1;
        
        HashMap<Character, Integer> map = new HashMap();
        for (int i = 0; i < size; i++){
            char value = str.charAt(i);
            if (! map.containsKey (value)) {// if the key value does not exist, a new key value with value of 1 will be created
                map.put(value, 1);
            }else{
                map.put (value,  map.get (value) + 1); // value plus one
            }
        }
        
        for (int i=0; i < size; i++){
            if (map.get(str.charAt(i)) == 1){
                return i;
            }
        }
        
        return -1;
    }
}

The second method: array method

public class Solution {
    public int FirstNotRepeatingChar(String str) {
        int size = str.length();
        if (size == 0) return -1;
        int[] array = new int[58];
        
        for (int i = 0; i< size; i++){
            array[(int)str.charAt(i)-65]++; 
        }
        
        for (int i= 0; i < size; i++){
            if (array[(int)str.charAt(i)-65] == 1){
                return i;
            }
        }
        
        
        return -1;
    }
} 

5. Python implementation

# -*- coding:utf-8 -*-
class Solution:
    def FirstNotRepeatingChar(self, s):
        # write code here
        if not s:
            return -1
        Hashes = {} ා uses hash table for storage
        alist = list(s)
        length = len(alist)
        
        for i in range(length):
            if not  hashes.get (alist [i]): ා if I doesn't exist
                hashes[alist[i]] = 1
            else:
                hashes[alist[i]] += 1
        
        for i in range(length):
            if hashes[alist[i]] == 1:
                return i 
        return -1

If you find this article useful, please click “like”

Reverse pairs of 35 arrays

First, let’s review the merge algorithm

Merging sorting algorithm flow:

(1) (2) set two pointers, the initial positions are respectively the starting positions of the two sorted sequences. (3) compare the elements pointed by the two pointers, select the relatively small elements into the merge space, and move the pointer to the next position (4) Repeat step 3 until a pointer reaches the end of the sequence (5). Copy all the remaining elements of the other sequence directly to the end of the merged sequence

The process of merging and sorting is as follows:

Take the array {50,10,90,30,70,40,80,60,20} as an example,

Seven days to brush your finger

public class Main {
    
    public static void MergeSort(int[] array, int low, int high){
        int mid = (low + high) / 2;
        if (low < high){
            MergeSort(array, low, mid);
            MergeSort(array, mid+1, high);
            
            //Sort
            Merge(array, low, mid, high);
        }
        
    }
    
    public static void Merge(int[] array, int low, int mid, int high){
        //Sort two ordered arrays
        Int left = low; // the first value of the array on the left
        Int right = mid + 1; // first value of array on the right
        int tmpIndex = 0;
        Int [] temparray = New Int [high low + 1]; // create a temporary array
        
        while (left <= mid && right <= high){
            if (array[left] < array[right]){ //Sort,如果左边值小于右边值,则先将左边数值放进临时数组
                tempArray[tmpIndex++] = array[left++];
            }else{
                tempArray[tmpIndex++] = array[right++];
            }
        }
        
        //If there are still numbers on the left, you need to put them all into the temporary array
        while (left <= mid){
            tempArray[tmpIndex++] = array[left++];
        }
        //If there are any more values on the right, you need to put them all into the temporary array
        while (right <= high){
            tempArray[tmpIndex++] = array[right++];
        }
        
        //Put the temp temporary array in the array to be sorted
        for (int index = 0; index < tempArray.length; index++){
            array[low + index] = tempArray[index];
        }
        
    }
    
    public static void main(String[] args) {
 
        //Implement a merge sort algorithm
        int[] array = {1, 4, 2, 7, 9, 5, 0};
        int size = array.length;
        Main.MergeSort(array, 0, size-1);
        for (int i=0; i<size; i++){
            System.out.println(array[i]);
        }
         
    }
}

1. Title Description

Two numbers in an array. If the first number is greater than the next, the two numbers form an inverse pair. Input an array to find the total number of reverse pairs P in this array. And output the result of P to 100000007. That is, output P% 100000007

Input Description:

The title ensures that the same number is not in the input array

Data range:

For% 50 data, size < = 10 ^ 4

For% 75 data, size < = 10 ^ 5

For% 100 data, size < = 2 * 10 ^ 5

2. Examples

input

1,2,3,4,5,6,7,0 output

7

3. Problem solving ideas

To find the reverse pair in an array, which can be regarded as the number of times that elements in the array need to be exchanged to sort the data. However, it is necessary to select a stable sorting method to record the times of exchange

Insertion, bubbling and merging are all stable, and merge algorithm is used here

Seven days to brush your finger

We take the array arr [4] = {7,5,6,4} as an example to analyze the process of statistical reverse pair. To avoid this, we consider comparing two adjacent numbers. We first decompose the array into two subarrays of length 2, and then divide the two subarrays into two subarrays of length 1.

In other words, arr [start, end] can be continuously split into two adjacent arrays of arr [start, mid] and arr [mid + 1, end], where mid = (start + end) / 2; until start > = end, that is, there is at most one element left in the current subarray of arr, so it is not necessary to split it again. At this time, there is no inverse pair in an element.

Next, while merging adjacent subarrays, count the number of reverse pairs. The simplest way is to establish the global variable count. In the first pair of subarrays {7}, {5} of length 1, 7 is greater than 5, so (7,5) forms an inverse pair. Similarly, in the second pair of subarrays {6}, {4} of length 1, there are also inverse pairs (6,4).

After the two pairs of sub arrays of {5,6} are sorted in reverse order to avoid repeating the two pairs of sub arrays of {5,6}. When {5,7} comes first and {4,6} comes after, we can sort the initial array, and the original array becomes {5,7,4,6}. If the original array cannot be modified, the array must be copied. Note: the copy form of int [] a = arr cannot be used.

Next, according to the modified original array arr [start, end] = {5,7,4,6}, count the reverse pairs between adjacent subarrays arr [start, mid] {5,7}, arr [mid + 1, end] {4,6}, In order to facilitate the merging operation, the reference array TMP is introduced. In order to avoid the new operation in the loop, a TMP array with the same size as the initial array can be created at the beginning, and then all merge operations share the same TMP;

First, two pointers I and j are established to point to the beginning of the subarray, i.e. I points to 5, J points to 4,

In this case: 7 is greater than 6, that is, arr [i] > arr [J]:

The index value of mid is 1, (5, 7, 4) constitutes two inverse pairs, forming mid – I + 1. Since the left array 57 is ordered, since the first bit on the left is greater than the first bit on the right, the second bit on the left must be greater than the first bit on the right. Therefore, the distance of the left array is calculated as mid-i with the interval of 1, and then the interval constant on the right is 1

4. Java implementation

public class Solution {
    private int count;
    
    public int InversePairs(int [] array) {
        count = 0;
        int size = array.length;
        if (size == 0 || size == 1) return 0;
        
        mergeSort(array, 0, size-1);
        return  count%1000000007;
        
    }
    
    private void mergeSort(int[] array, int low, int high){
        int mid = (low + high) / 2;
        if (low < high){
            mergeSort(array, low, mid);
            mergeSort(array, mid+1, high);
 
            merge(array, low, mid, high);
        }
        
    }
    
    private void merge(int[] array, int low, int mid, int high){
        int i = low;
        int j = mid + 1;
        int tempIndex = 0;
        int[] tempArray = new int[high-low+1];
        
        while (i <= mid && j <= high){
            if (array[i] <= array[j]){
                tempArray[tempIndex++] = array[i++];
            }else{
                tempArray[tempIndex++] = array[j++];
                count += mid - i + 1;
                count %= 1000000007;
            }
        }
        
        while (i <= mid){
            tempArray[tempIndex++] = array[i++];
        }
        
        while (j <= high){
            tempArray[tempIndex++] = array[j++];
        }
        
        for (int index = 0; index < tempArray.length; index++){
            array[low + index] = tempArray[index];
        }
    }
    
} 

5. Python implementation

class Solution:
 
    def InversePairs(self, data):
        if not data or len(data) == 1:
            return data
        copy = [0] * len(data)
        count = self.InversePairsCore(data, copy, 0, len(data)-1)
        # print(copy)
        return count
 
    def InversePairsCore(self, data, copy, low, high):
        if low == high:
            return 0
        mid = (high + low) // 2
        leftCount = self.InversePairsCore(data, copy, low, mid) % 1000000007
        rightCount = self.InversePairsCore(data, copy, mid+1, high) % 1000000007
        count = 0
        i, j = mid, high
        locCopy = high
        while i >= low and j > mid:
            if data[i] > data[j]:
                count += j - mid
                copy[locCopy] = data[i]
                locCopy -= 1
                i -= 1
                if count >= 1000000007:
                    count %= 1000000007
            else:
                copy[locCopy] = data[j]
                locCopy -= 1
                j -= 1
        for ii in range(i, low-1, -1):
            copy[locCopy] = data[ii]
            locCopy -= 1
        for jj in range(j, mid-1, -1):
            copy[locCopy] = data[jj]
            locCopy -= 1
        for s in range(low, high+1):
            data[s] = copy[s]
        return leftCount + rightCount + count 

If you find this article useful, please click “like”

36 the first common node of two linked lists

1. Title Description

Enter two linked lists to find their first common node. (note that since the incoming data is a linked list, the prompt of error test data is displayed in other ways to ensure that the incoming data is correct)

2. Examples

Common node means that after two linked lists meet, they are the same

3. Problem solving ideas

Idea: first get the length of the two linked lists, and then the long list takes a few more steps, and then traverses them together

Suppose that the common length of two linked lists is C, and the length not shared is a and B respectively. Then the lengths of the two lists are a + C and B + C respectively. Set two pointer, let the first list finish, jump to the second linked list to start, a total of A+C+X1 distance; similarly, after the second linked list finished, transfer to the first list to start, go B+C+X2 distance.

Then when two pointers meet, if the distance is not negative from a + C + X1 = B + C + X2, then X1 = a, X2 = B. therefore, the distance between the last two pointers is a + B + C, which happens to meet at the first common point.

4. Java implementation

/*
public class ListNode {
    int val;
    ListNode next = null;
    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        if (pHead1 == null || pHead2 == null) return null;
        ListNode p1 = pHead1;
        ListNode p2 = pHead2;
        int size1 = getLinkLenth(p1);
        int size2 = getLinkLenth(p2);
        
        While (Size1 > size2) {// if the linked list 1 is long, the Size1 - size2 steps are taken first
            pHead1 = pHead1.next;
            size1 -= 1;
        }
        
        while (size1 < size2){
            pHead2 = pHead2.next;
            size2 -= 1;
        }
        
        While (phead1! = null) {// if two nodes are found to be equal, there is a common node
            if (pHead1 == pHead2){
                return pHead1;
            }
            pHead1 = pHead1.next;
            pHead2 = pHead2.next;
        }
        return null;
    }
    
    Private int getlinklenth (listnode root) {// calculates the length of the linked list
        if (root == null) return 0;
        if (root.next == null) return 1;
        int res = 0;
        while (root != null){
            res += 1;
            root = root.next;
        }
        return res;
    }
}

5. Python implementation

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def FindFirstCommonNode(self, pHead1, pHead2):
        # write code here
        if not pHead1 or not pHead2:
            return 
        
        move1, move2 = pHead1, pHead2
        length1, length2 = 0, 0
        While move1: calculate the length of linked list 1
            length1 += 1
            move1 = move1.next 
            
        While move2: # calculate the length of the chain table 2
            length2 += 1
            move2 = move2.next 
        
        while length1 > length2:
            pHead1 = pHead1.next 
            length1 -= 1
        
        while length2 > length1:
            pHead2 = pHead2.next 
            length2 -= 1
            
        While phead1: two linked lists go forward together
            if pHead1 == pHead2:
                return pHead1
            pHead1, pHead2 = pHead1.next, pHead2.next 
            
        return None

If you find this article useful, please click “like”

37 the number of times a number appears in a sorted array

1. Title Description

Count the number of times a number appears in an ascending array.

2. Examples

For example: 1, 2, 4, 6, 7, 7, 7, 8, 10

The frequency of occurrence was 3

3. Problem solving ideas

Ideas:

Seven days to brush your finger

Use dichotomy to find the coordinates of the first and last values in the array, and subtract + 1

4. Java implementation

public class Solution {
    public int GetNumberOfK(int [] array , int k) {
        int size = array.length;
        if (size == 0) return 0;
        int firstK = getFirstK(array, k);
        int lastK = getLastK(array, k);
        If (firstk = = - 1 & & lastk = = - 1) return 0; // if K is not found before and after, then there is no K
        If (firstk = = - 1 | lastk = = - 1) return 1; // if only one item is found, there is only 1 K
        return lastK - firstK + 1;
    }
    
    Private int getfirstk (int [] array, int k) {// gets the first index value of K value
        int size = array.length;
        int start = 0, end = size-1;
        
        while (start <= end){
            int mid = (start + end) / 2;
            if (array[mid] < k){
                //Determine whether the next mid + 1 is equal to K
                if (mid+1<size && array[mid+1] == k){
                    return mid+1;
                }
                Start = mid + 1; // search right half
            }Else if (array [mid] = = k) {// since we need to find the index value of the first k, we still need to judge
                //1. If the mid is 0, it will return directly; 2. If the previous mis-1 value is less than k, it will return the mid directly
                if (mid - 1<0 ||(mid - 1>=0 && array[mid-1] < k)){
                    return mid;
                }
                End = mid - 1; // at this time, K may be on the left, and search the left
            }else{
                end = mid-1;
            }
        }
        return -1;
    }
    
    private int getLastK(int[] array, int k){
        int size = array.length;
        int start = 0, end = size-1;
        
        while (start <= end){
            int mid = (start + end) / 2;
            if (array[mid] < k){
                start = mid + 1;
            }Else if (array [mid] = = k) {// find the index value of the rightmost K
                //1. If mid is on the far right, return 2. If mid + 1 value is less than k, return mid
                if (mid+1 == size || (mid + 1 < size && array[mid+1] > k)){
                    return mid;
                }
                Start = mid + 1; // search right
            }else{
                //If the previous value is exactly equal to K
                if (mid -1 >= 0 && array[mid-1] == k){
                    return mid -1;
                }
                end = mid - 1;
            }
        }
        return -1;
        
    }
}

5. Python implementation

# -*- coding:utf-8 -*-
class Solution:
    def GetNumberOfK(self, data, k):
        # write code here
        #return data.count(k)
        if not data:
            return 0
        
        left = self.get_first_k(data, k)
        right = self.get_last_k(data, k)
        if left < 0 and right < 0:
            return 0
        If left < 0 or right < 0:
            return 1 
        return right -left + 1
        
        
    def get_first_k(self, data, k):
        left, right = 0, len(data)-1
        while left <= right:
            mid = (left + right) // 2
            if data[mid] < k:
                If mid + 1 < len (data) and data [mid + 1] = = k: if the last digit is equal to K
                    return mid + 1
                left = mid + 1
            elif data[mid] == k:
                If mid-1 < 0 or (mid-1 > = 0 and data [mid-1] < K): ා make sure to get the first index on the left, if mid-1 is 0, if the previous value is less than k
                    return mid 
                right = mid - 1
            else:
                right = mid - 1
        return -1
                
    def get_last_k(self, data, k):
        left, right = 0, len(data)-1
        while left <= right:
            mid = (left + right) // 2
            if data[mid] < k:
                left = mid + 1
            elif data[mid] == k:
                If mid + 1 = = len (data) or (mid + 1 < len (data) and data [mid + 1] > k): # if the index is length-1, if the last bit is greater than k
                    return mid 
                left = mid + 1
            Else: if the intermediate value is greater than k
                if mid -1 >= 0 and data[mid-1] == k:
                    return mid -1 
                right = mid - 1
        return -1

If you find this article useful, please click “like”

Seven days to brush your finger

Recommended Today

The usage of raiserror function in SQL Server database

The usage of raiserror function in SQL Server database serverdatabaseThe function of raiserror in ASP.NETLike throw new exception in, it is used to throw an exception or error. This error can be caught by the program. The common format of raiserror is as follows:Raiserrror (‘error description ‘, error severity code, error identification, parameter values in […]