Brush offer to prove safety issues Summary - array of articles (five)

1. Digital frequency appears in the sorted array

【topic】

Count the number of times a number that appears in the sort array.

[Code]

public int GetNumberOfK(int [] array , int k) {

        if (array.length==0 || array==null) return 0;

        int i,n,count;
        n = array.length;

        count = 0;
        for (i=0; i<n; i++) {
            if (array[i] == k) count++;
        }

        return count;
    }

    public int high(int[] a, int k) {
        int start,end,mid;

        start = 0;
        end = a.length-1;

        while (start <= end) {
            mid = (start + end) >> 1;
            if (a[mid] <= k) {
                start = mid + 1;
            } else {
                end = mid - 1;
            }
        }

        return end;
    }

    public int low(int[] a, int k) {
        int start,end,mid;

        start = 0;
        end = a.length-1;

        while (start <= end) {
            mid = (start + end) >> 1;
            if (a[mid] >= k) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }

        return start;
    }

[Thinking]

Since the array is a sorted array, it is possible to use a binary search, the appearance position of the positioning k and last occurrence position, the time complexity of O (logN) O (logN)

Dichotomous premise: Ordered (a reference to an orderly, must immediately think of half!)


2. seeking 1 + 2 + 3 + ... + n

【topic】

Seeking 1 + 2 + 3 + ... + n, requires multiplication and division can not be used, for, while, if, else, switch, case and keywords such as conditional statement (A B:? C).

[Code]

	public int Sum_Solution(int n) {
        int sum = n;
        boolean flag = (sum > 0) && (sum += Sum_Solution(n-1))>0;
        return sum;
    }

[Thinking]

Cycles required can not be used, can not be used is determined, so a recursive loop in place, instead of a short circuit is determined by the principle

The order of execution is left to right and short-circuit, after determining that the first expression is false there is no need to perform the necessary conditions for the second sentence of the. Because obviously, whether true or false second condition, the Boolean value of the entire expression must be false. Participants jump off the second short-circuit condition sentence, do not execute it. Based on these principles, giving rise to the above results. In programming, flexible use of a short circuit with a lot of sense.

When n = 0,, sum = 0, && will not be executed later, direct return sum = 0

He published 196 original articles · won praise 878 · Views 300,000 +

Guess you like

Origin blog.csdn.net/qq_33945246/article/details/104578970