国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

Hackerrank Practice

arashicage / 2723人閱讀

摘要:數(shù)組中重復元素的個數(shù)題目找到一個數(shù)組中重復元素的個數(shù)。能否成為題目互減,直到的時候。此方法精彩此方法更精彩找兩邊相等的

Anagram 拆分數(shù)組 看一半操作幾次能成為另一半的anagram 題目

輸入第一行是要判斷的字符串的個數(shù)n,之后的n行輸入為需要判斷的字符串。
每個字符串str,是兩個等長字符串的合體,所以長度一定是偶數(shù)。若為奇數(shù),返回-1。
所以str分成兩個substring,右邊需要多少次操作能變?yōu)樽筮叀V灰靡粋€26位的數(shù)組統(tǒng)計每個字符在a和b中出現(xiàn)的次數(shù)就行,在a中出現(xiàn)+1,在b中出現(xiàn)-1,最后統(tǒng)計數(shù)組的26位元素的絕對值除以2,就是要進行操作的次數(shù)。

?Input Format

The first line will contain an integer T representing the number of test cases. Each test case will contain a string having length (a+b) which will be concatenation of both the strings described in problem. The string will only contain small letters and without any spaces.

?Output Format

An integer corresponding to each test case is printed in a different line i.e., the number of changes required for each test case. Print ‘-1’ if it is not possible.
?Constraints
1?≤?T?≤?100??1 ≤?a+b?≤?10,000
?
Sample Input

5
aaabbb
ab
abc
mnop
xyyx

Sample Output

3
1
-1
2
0 

?Explanation

In the five test cases

One string must be “aaa” and the other “bbb”. The lengths are?a=3?and?b=3, so the difference is less than 1. No characters are common between the strings, so all three must be changed.

One string must be “a” and the second “b”. The lengths are?a=1?and?b=1,?so the difference is less than 1. One character must be changed to them the same.

Since the string lengths?a?and?b?must differ by no more than 1, the lengths are either a=1?and?b=2?or a=2?and?b=1.No sequence of substitutions will make the two ?anagrams of one another.

One string must be?“mn" and other be “op”. The length are?a=2?and?b=2, so the difference is less than 1. Nocharacters are common between the strings, so both must be changed.

One string must be “xy” and the other be “yx”. The length are a=2 and b=2, so the difference is less than 1. No changes are needed because the second string is already an anagram of the first.
Collapse Question

import java.io.*;
import java.util.*;
public class Solution {
    public static void main(String args[] ) throws Exception {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT */
        Scanner in = new Scanner(System.in);
        String str = in.nextLine();
        int num = Integer.parseInt(str);
        String[] strs = new String[num];
        for (int i = 0; i < num; i++) {
            strs[i] = in.nextLine();
        }
        for (String s: strs) {
            int res = validate(s);
            System.out.println(res);
        }
    }
public static int validate(String str) {
    if (str.length() % 2 == 1) return -1;
    int len = str.length();
    String a = str.substring(0, len/2);
    String b = str.substring(len/2);
    int[] ch = new int[26];
    for (int i = 0; i < a.length(); i++) {
        char ca = a.charAt(i);
        char cb = b.charAt(i);
        if (ca < "a" || ca > "z" || cb < "a" || cb > "z") return -1;
        ch[ca-"a"]++;
        ch[cb-"a"]--;
    }
    int count = 0;
    for (int c: ch) {
        if (c == 0) continue;
        count += Math.abs(c);
    }
    return count/2;
}
}
Count Duplicates 數(shù)組中重復元素的個數(shù) 題目

找到一個數(shù)組中重復元素的個數(shù)。
?
Complete the countDuplicates function in the editor below. It has 1 parameter: an array of integers, numbers. It must return an integer denoting the number of non-unique values in the numbers array.
?
Constraints

1 ≤ n ≤ 1000

1 ≤ numbersi ≤ 1000

Solution
    static int countDuplicates(int[] numbers) {
        Map map = new HashMap<>();
        for (int key: numbers) {
            if (map.get(key) == null) map.put(key, 1);
            else map.put(key, map.get(key)+1);
            //map.put(key, map.getOrDefault(key, 0)+1);
        }
        int count = 0;
        for (Map.Entry entry: map.entrySet()) {
            if (entry.getValue() > 1) count++;
        }
        return count;
    }

或者用數(shù)組

    static int countDuplicates(int[] numbers) {
        int[] n = new int[1000];
        Arrays.fill(n, 0);
        int count = 0;
        for (int i: numbers) {
            if (n[i] == -1) continue;
            else if (n[i] == 0) n[i]++;
            else { // actually n[i] = 1
                n[i] = -1;
                count++;
            }
        }
        return count;
    }
HackLand Election 誰選票多且名字靠后 題目

n個人投票,名字(票數(shù))最多的獲勝,若票數(shù)相同,名字字母順序靠后的獲勝。

Solution
    static String electionWinner(String[] votes) {
        Map map = new HashMap<>();
        int max = 0;
        for (String vote: votes) {
            if (map.get(vote) == null) map.put(vote, 1);
            else {
                int count = map.get(vote)+1;
                map.put(vote, count);
                max = Math.max(max, count);
            }
            //map.put(vote, map.getOrDefault(vote, 0)+1);
        }
        List res = new ArrayList<>();
        for (Map.Entry entry: map.entrySet()) {
            if (entry.getValue() == max) res.add(entry.getKey());
        }
        Collections.sort(res);
        return res.get(res.size()-1);
    }
Delete Nodes Greater Than X 鏈表按值刪除結點 題目

從鏈表里刪除所有值大于X的結點。
需要dummy結點,用cur.next.val去比大小。

Solution
    static LinkedListNode removeNodes(LinkedListNode list, int x) {
        LinkedListNode dummy = new LinkedListNode(0);
        dummy.next = list;
        LinkedListNode cur = dummy;
        while (cur.next != null) {
            if (cur.next.val > x) {
                cur.next = cur.next.next;
            }
            else cur = cur.next;
        }
        return dummy.next;
    }
Even Odd Query 數(shù)組里取x,y 看pow(x,y)奇偶性 題目

其實就是給一個數(shù)組,然后給一些index pair,看數(shù)組中對應index的兩個數(shù)的pow(x, y)是奇數(shù)還是偶數(shù)。

Input Format

?The first line contains an integer N.
The next line contains N space separated single-digit integers (whole numbers between 0 and 9).?The third line contains a positive integer?Q, denoting the number of queries to follow.
Each of the subsequent Q?lines contains two positive integers?x and y separated by a single space.
?
Output Format

?For each query, print the ?"Even"??if the value returned is even, otherwise print "Odd " without quotes.
?
Sample Input #00

3
3 2 7
2
1 2
2 3

?
Sample Output #00

Odd
Even

?
Explanation #00

find(1,2) = 3^2?= 9, which is odd.
?find(2,3) = 2^7 = 128, which is even.
Solution
import java.io.*;
import java.util.*;
public class Solution {
    public static void main(String args[] ) throws Exception {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT */
        //BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        //int N = Integer.parseInt(br.readLine());
        StringBuffer sb = new StringBuffer();
        Scanner in = new Scanner(System.in);
        int N = Integer.parseInt(in.nextLine());
        int[] A = new int[N];
        String[] strs = in.nextLine().split(" ");
        for (int i = 0; i < N; i++) {
            A[i] = Integer.parseInt(strs[i]);
        }
        for (int i = Integer.parseInt(in.nextLine()); i > 0; i--) {
            strs = in.nextLine().split(" ");
            int m = Integer.parseInt(strs[0])-1;
            int n = Integer.parseInt(strs[1])-1;
            int base = A[m];
            int power = (m == n) ? 1 : A[m+1];
            if (power == 0 || (base & 1) == 1) sb.append("Odd
");
            else sb.append("Even
");
        }
        System.out.print(sb);
    }
}
The Bit Game 在某區(qū)間內最大的兩數(shù)XOR值 題目

在l和r之間取兩個數(shù)x,y,使他倆的異或值<=k且最大,返回這個值。

Solution
    static int maxXor(int l, int r, int k) {
        if (l == r) return 0;
        if (l > r) return maxXor(r, l, k);
        int max = 0;
        for (int i = l; i <= r; i++) {
            for (int j = l; j <= r; j++) {
                if ((i ^ j) > k) continue;
                max = Math.max(max, i ^ j);
            }
        }
        return max;
    }
Element Present in BST Tree 在BST里找元素 題目

看一個BST里有沒有值為val的元素,有返回1,沒有返回0。
用cur去遍歷,用pre存儲cur在本次循環(huán)起始的位置,誰知道cur.left和cur.right存在不存在呢,對吧。

Solution
    private static int isPresent(Node root, int val){
        Node pre = root, cur = root;
        while (cur != null) {
            pre = cur;
            if (cur.val == val) return 1;
            else if (cur.val < val) cur = cur.right;
            else cur = cur.left;
        }
        if ((pre.left != null && pre.left.val == val) || (pre.right != null && pre.right.val == val)) return 1;
        return 0;
    }
Pangrams 題目

給一些字符串,看是不是pangram,即包含全部26個字母的句子。是就返回1,不是就返回0.

Solution
    static String isPangram(String[] strings) {
        StringBuilder sb = new StringBuilder();
        for (String str: strings) {
            int[] pan = new int[26];
            Arrays.fill(pan, 0);
            for (int i = 0; i < str.length(); i++) {
                char ch = str.charAt(i);
                if (ch >= "a" && ch <= "z") pan[ch-"a"]++;
            }
            for (int i = 0; i < 26; i++) {
                if (pan[i] == 0) {
                    sb.append("0");
                    break;
                }
                if (i == 25 && pan[i] != 0) sb.append("1");
            }
        }
        return sb.toString();
    }
Cut the Sticks 每次按最短那根的長度切所有木頭,每次切完記錄剩余的木頭數(shù) 題目

有N條木段,每次切割必須這樣:把所有的木段都切掉最短的那條木段的長度。每次切割后記錄剩余木段的條數(shù),最短的木段肯定沒了嘛,如此重復,直到都被切禿嚕了(為0)。

Sample Case:

    lengths       cut length   count cuts
1 2 3 4 3 3 2 1       1           8
_ 1 2 3 2 2 1 _       1           6
_ _ 1 2 1 1 _ _       1           4
_ _ _ 1 _ _ _ _       1           1
_ _ _ _ _ _ _ _     DONE        DONE
Solution
    static int[] cutSticks(int[] lengths) {
        int n = lengths.length;
        Arrays.sort(lengths);
        List ans = new ArrayList<>();
        for (int i = 0; i < n; i++) {
            if (lengths[i] == 0) continue;
            else {
                ans.add(n-i);
                int temp = lengths[i];
                for (int j = i; j < n; j++) {
                    lengths[j] -= temp;
                }
            }
        }
        int[] res = new int[ans.size()];
        for (int i = 0; i < ans.size(); i++) res[i] = ans.get(i);
        return res;
    }
Prime or Not? 判斷質數(shù) 返回最大因數(shù) 題目

是質數(shù),返回1;不是質數(shù),返回最大因數(shù)。

Solution
    static int isPrime(long n) {
        if (n <= 2) return 1;
        else if (n > 2 && n % 2 == 0) return 2;
        for (int i = 2; i <= n/2; i++) {
            if (n % i == 0) return i;
        }
        return 1;
    }
Reduce the Fraction 約分 約分 解法

找最大公約數(shù),分子和分母都除以公約數(shù)后加入StringBuilder,再添加到結果數(shù)組即可。

    static String[] ReduceFraction(String[] fractions) {
        String[] res = new String[fractions.length];
        for (int i = 0; i < fractions.length; i++) {
            String[] nums = fractions[i].split("/");
            int[] n = new int[2];
            n[0] = Integer.parseInt(nums[0]);
            n[1] = Integer.parseInt(nums[1]);
            
            StringBuilder sb = new StringBuilder();
            sb.append(n[0]/(GCD(n[0], n[1]))+"/"+n[1]/(GCD(n[0], n[1])));
            res[i] = sb.toString();
        }
        return res;
    }
    static int GCD(int n1, int n2) {
        if (n2 == 0) return n1;
        return GCD(n2, n1%n2);
    }
Pascal"s Triangle 帕斯卡三角

Pascal’s Triangle
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
....

題目

給出層數(shù)n,print出帕斯卡三角形。

Solution
    static void pascalTriangle(int k) {
        for (int i = 0; i < k; i++) {
            for (int j = 0; j <= i; j++) {
                System.out.print(pascal(i, j) + " ");
            }
            System.out.println();
        }

    }
    static int pascal(int i, int j) {
        if (j == 0) return 1;
        if (i == j) return 1;
        return pascal(i-1, j-1) + pascal(i-1, j);
    }
Calculate Factorial 破階乘

n前面要用(long)哦。

Solution
    static long factorial(int n) {
        long res = 1;
        if (n <= 0) return 0;
        while (n != 0) {
            res *= (long)n;
            n--;
        }
        return res;
    }
Angry Children 給小孩發(fā)糖果 令分配公平不懸殊 題目

N包糖,里面的糖果數(shù)不同,挑k包,分給k個孩子,要求找到最小的分配糖果差值。
Sample Input #2

4 //children
10 //packet #
1 2 3 4 10 20 30 40 100 200
?
Sample Output #2

3
?
Explanation #2

?Here K = 4. We can choose the packets that contain 1,2,3,4 candies.
The unfairness is max(1,2,3,4) - min(1,2,3,4) = 4 - 1 = 3

Solution
    static int minUnfairness(int k, int[] arr) {
        //actually find the min of arr[i+k-1]-arr[i]
        Arrays.sort(arr);
        int n = arr.length;
        int min = arr[n-1];
        for (int i = 0; i < n-k+1; i++) {
            min = Math.min(min, arr[i+k-1]-arr[i]);
        }
        return min;
    }
Is Possible AKA Can Reach (a,b)能否成為(c,d) 題目

Consider a pair of integers, (a, b). We can perform the following operations on (a, b) in any order, zero or more times:

(a, b) → (a + b, b)

(a, b) → (a, a + b)

Solution

c, d互減,直到c <= a && d <= b的時候。
若此時c == a && d == b,說明a, b的確可以變成c, d.

    static String isPossible(int a, int b, int c, int d) {
        while (c > a || d > b) {
            if (c > d) {
                c -= d;
                if (c < a) return "No";
            }
            else {
                d -= c;
                if (d < b) return "No";
            }
        }
        if (a == c && b == d) return "Yes";
        else return "No";
    }
Encircular 旋轉的機器人能否回到我們的原點

G instructs the robot to move forward one step.

L instructs the robot to turn left.

R instructs the robot to turn right.

題目

循環(huán)執(zhí)行轉彎、前進的一串動作,能否回到原點?告訴你,只和角度有關。一個L,就是90°,再來一個R,就把它抵消了,那就回不去了。最后剩下的L為奇數(shù)個,就回得去。

Solution
    static String[] doesCircleExist(String[] commands) {
        int len = commands.length;
        String[] res = new String[len];
        for (int i = 0; i < len; i++) {
            res[i] = valid(commands[i]);
        }
        return res;
    }
    static String valid(String com) {
        int l = 0;
        for (int i = 0; i < com.length(); i++) {
            char ch = com.charAt(i);
            if (ch == "G") continue;
            if (ch == "L") l++;
            if (ch == "R") l--;
        }
        if (l % 2 == 0) return "NO";
        else return "YES";
    }
Circle 題目

給一堆齒輪找各自符合組合標準且造價最低的那個齒輪的index。
循環(huán),每個齒輪,找合適的另一個齒輪分兩步:先找到符合尺寸標準的所有齒輪,再從這些齒輪中找到造價最低的那個,將index加入結果數(shù)組。

Solution
    static int[] Circles(int distance, int[] radius, int[] cost) {
        int[] result = new int[radius.length];
        for (int i = 0; i < radius.length; i++) {
            List tmp = new ArrayList();
            for (int j = 0; j < radius.length; j++) {
                if (radius[j] >= distance - radius[i]) tmp.add(j);//添加滿足尺碼的index
            }
            result[i] = getSmallest(cost, tmp, i);
        }
        return result;
    }

    static int getSmallest(int[] cost, List tmp, int i) {
        if (tmp.size() == 0) return 0;
        int index = tmp.get(0);
        int mincost = cost[tmp.get(0)];
        for (int j = 1; j < tmp.size(); j++) {
            if (cost[tmp.get(j)] < mincost) {
                mincost = cost[tmp.get(j)];
                index = tmp.get(j);
            }
        }
        return index+1;
    }

?

List Max 著名的Prefix Sum 題目

不斷給某個區(qū)間做加同一個數(shù)的操作,問最后最大的數(shù)變成了多少。

Sample Input 0
5 3
1 2 100
2 5 100
3 4 100
?
Sample Output 0
200
?
Explanation 0
We perform the following sequence of m = 3 operations on list = {0, 0, 0, 0, 0}:

Add k = 100 to every element in the inclusive range [1, 2], resulting in list = {100, 100, 0, 0, 0}.

Add k = 100 to every element in the inclusive range [2, 5], resulting in list = {100, 200, 100, 100, 100}.

Add k = 100 to every element in the inclusive range [3, 4], resulting in list = {100, 200, 200, 200, 100}.
We then print the maximum value in the final list, 200, as our answer.

import java.io.*;
import java.util.*;
public class Solution {
    public static void main(String args[] ) throws Exception {
        Scanner in = new Scanner(System.in);
        int size = in.nextInt(); //size of array
        int m = in.nextInt(); //# of operations
        //marking array
        long[] arr = new long[size+1]; //allocate one more space for the last digit to sum up
        for (int i = 0; i < m; i++) {
            int a = in.nextInt();
            int b = in.nextInt();
            int k = in.nextInt();
            arr[a-1] += k; //only mark the starting index that changed
            arr[b] -= k; //從這往后的最后都會被加上之前的sum,所以提前減掉 
        }
        long max = Long.MIN_VALUE; //用long哦  
        long sum = 0;
        for (int i = 0; i < size; i++) {
            sum += arr[i];
            max = Math.max(max, sum);
        }
        System.out.println(max);
    }
}
Number Complement 找一個數(shù)的補碼

找到最高位,建立掩碼mark取反

    static int getIntegerComplement(int n) {
        int high = (int)(Math.log(n)/Math.log(2));
        int mark = (1 << (high+1))-1;
        return n ^ mark;
    }
The Love-Letter Mystery 題目

letter的每一個句子是一個字符串,我們要計算將這些字符串轉變?yōu)榛匚淖址牟僮鞔螖?shù)。
例如a-->c,要走兩次哦。那么"abc"的步數(shù)就是2,"abcd"的步數(shù)就是3+1=4.

    static int[] mystery(String[] letter) {
        if (letter == null || letter.length == 0) return new int[0];
        if (letter.length == 1) {
            int[] a = new int[1];
            a[0] = 0;
            return a;
        }
        int[] res = new int[letter.length];
        for (int i = 0; i < letter.length; i++) {
            String str = letter[i];
            int op = helper(str);
            res[i] = op;
        }
        return res;
    }
    static int helper(String str) {
        int n = str.length();
        int left = 0, right = n-1;
        int count = 0;
        while (left < right) {
            count += Math.abs(str.charAt(right) - str.charAt(left));
            left++;
            right--;
        }
        return count;
    }
Metals 章魚賣鐵 咋切最賺
    static int maxProfit(int cost_per_cut, int metal_price, int[] lengths) {
        int maxLength = 0;
        //找最長的鐵塊
        for (int length : lengths) {
            if (length > maxLength) {
                maxLength = length;
            }
        }
        int maxProfit = 0;
        for (int i = 1; i < maxLength; i++) {
            int sumOfLengths = 0;
            int sumOfCutCounts = 0;
            int sumOfCutWastes = 0;
            for (int length : lengths) {
                sumOfLengths += length;
                if (length % i == 0) {
                    sumOfCutCounts += (length/i - 1); //總長被定長整除,可以少切一次
                } else {
                    sumOfCutCounts += (length/i);
                }
                sumOfCutWastes += (length%i); //統(tǒng)計浪費的零頭
            }
            int profit = sumOfLengths*metal_price - sumOfCutCounts*cost_per_cut - sumOfCutWastes*metal_price; //總價 - 切割費用 - 浪費材料價值
            if (profit > maxProfit) {
                maxProfit  = profit; //更新最大利潤
            }
        }
        return maxProfit;
    }


#Gem Stones 有幾個字符在所有字符串都出現(xiàn)了呢
static int gemstones(String[] rocks) {
    Set set = new HashSet<>(26);            
    Set cur = new HashSet<>(26);
    char[] init = rocks[0].toCharArray();
    for (char ch: init) set.add(ch);
    for (String rock: rocks) {
        for (char ch: rock.toCharArray()) {
            cur.add(Character.valueOf(ch));
        }
        set.retainAll(cur);
        cur.clear();
    }
    return set.size();
}




Valid BST using Pre-traversal

import java.io.*;
import java.util.*;

public class Solution {

public static void main(String args[] ) throws Exception {
    Scanner in = new Scanner(System.in);
    int n = Integer.parseInt(in.nextLine());
    for (int i = 0; i < n; i++) {
        int len = Integer.parseInt(in.nextLine());
        int[] nodes = new int[len];
        String[] str = in.nextLine().split(" ");
        for (int j = 0; j < len; j++) {
            nodes[j] = Integer.parseInt(str[j]);
        }
        if (validBST(nodes, 0, len-1)) System.out.println("YES");
        else System.out.println("NO");
    }
}
public static boolean validBST(int[] A, int start, int end) {
    if (end <= start) return true;
    int root = A[start];
    int i = start+1;
    while (i <= end && A[i] < root) i++; //第一個大于root的數(shù),只能是右子樹root.right
    int right = i; 
    while (i <= end && A[i] > root) i++;
    if (i != end+1) return false; //右子樹有小于等于root的結點,上面的while提前結束了
    return validBST(A, start+1, right-1) && validBST(A, right, end); //左子樹OK && 右子樹OK
}

}




#Is this a tree? 難題
public static String SExpression(String s){
    boolean[][] graph = new boolean [26][26];
    HashSet nodes = new HashSet<>();
    //construct graph and check error E2: duplicate edges
    boolean E2 = false;
    for(int i=1;i2)
            return "E1";
    }
    if(E2) return "E2"; //return E2 after checking E1
    
    //check E3: cycle present and E4: multiple roots
    int numOfRoots = 0;
    char root =" ";
    for (char node: nodes){ //only check char that in the tree
        for(int i=0;i<26;i++){
            if(graph[i][node-"A"])
                break;
            if(i==25){
                numOfRoots++;
                root = node;
                boolean[] visited = new boolean[26];
                if(IsCycle(node, graph, visited))
                    return "E3";
            }
        }
    }
    if(numOfRoots==0) return "E3"; //if no root, must be a cycle
    if(numOfRoots>1) return "E4"; //if more than one roots
    if(root==" ") return "E5"; //if no edge in input string, invalid input error
    return GetExpressionHelper(root, graph);
    
}

//true means there is a cycle, false means no cycle
private static boolean IsCycle(char node, boolean[][] graph, boolean[] visited){
    if(visited[node-"A"]) //node has already been visited, must has a cycle
        return true;
    visited[node-"A"] = true;
    for(int i=0;i<26;i++){
        if(graph[node-"A"][i]){
            if(IsCycle((char)(i+"A"), graph, visited))
                return true;
        }
    }
    return false;
}

//Recursive DFS to get the expression/construct the tree
private static String GetExpressionHelper(char root, boolean[][] graph){
    String left = "", right = ""; //if no children, left and right should be empty
    for(int i=0;i<26;i++){
        if(graph[root-"A"][i]){
            left = GetExpressionHelper((char)(i+"A"), graph);
            for(int j=i+1;j<26;j++){
                if(graph[root-"A"][j]){
                    right = GetExpressionHelper((char)(j+"A") ,graph);
                    break;
                }
            }
            break;
        }
    }
    return "("+root+left+right+")";
}


#K-Difference 這是Two Sum的變種
static int kDifference(int[] a, int k) {

    int n = a.length;
    int count = 0;
    Arrays.sort(a);
    for(int i=0; i

#Maximum Difference in an Array -- Nice

數(shù)組中任意兩元素的最大差值,必須是后面的減前面的。

brute force -- TLE
static int maxDifference(int[] a) {
    if (a == null || a.length < 2) return 0;
    int max = -1;
    int n = a.length;
    for (int i = 0; i < n-1; i++) {
        for (int j = i+1; j < n; j++) {
            if (a[j] > a[i]) max = Math.max(max, a[j]-a[i]);
        }
    }
    return max;
} 
**此方法精彩**
static int maxDifference(int[] a) {
    if (a == null || a.length < 2) return 0;
    int n = a.length;
    int res = -1;
    for (int i = 0; i < n; i++) {
       int maxIndex = getmax(a, i);
       int minIndex = getmin(a, i, maxIndex);
       if (a[maxIndex]-a[minIndex] > res) res = a[maxIndex]-a[minIndex] > 0 ? a[maxIndex]-a[minIndex] : -1;
       i = maxIndex+1;
    }
    return res;
}
static int getmax(int[] a, int start) {
    int maxIndex = start;
    for (int i = start; i < a.length; i++) {
        if (a[i] > a[maxIndex]) maxIndex = i;
    }
    return maxIndex;
}
static int getmin(int[] a, int start, int end) {
    int minIndex = start;
    for (int i = start+1; i <= end; i++) {
        if (a[i] < a[minIndex]) minIndex = i;
    }
    return minIndex;
}
**此方法更精彩**
static int maxDifference(int[] a) {
    if (a == null || a.length < 2) return 0;
    int n = a.length;
    int res = -1;
    int min = a[0];
    for (int i = 0; i < n; i++) {
        if (a[i] < min) min = a[i];
        else {
            if (a[i]-min > 0) res = Math.max(res, a[i]-min);
            else continue;
        }
    }
    return res;
}
#Sum of Two Numbers in an Array (sum = k)

Your function must return the number of pairs of `unique/distinct` pairs in a having a sum equal to k.
?
static int numberOfPairs(int[] a, long k) {
    Arrays.sort(a);
    int n = a.length;
    int i = 0, j = n-1;
    int count = 0;
    while (i < j) {
        while (i > 0 && a[i] == a[i-1]) i++; //skip the duplicate
        while (j < n-1 && a[j] == a[j+1]) j--; //skip the duplicate
        long sum = a[i]+a[j];
        if (sum == k) {
            count++;
            i++;
            j--;
        }
        else if (sum < k) i++;
        else j--;
    }
    return count;
}

#Balance the Array 找兩邊sum相等的index
static int balanceSum(int[] A) {
    int[] sum = new int[A.length];
    sum[0] = A[0];
    for (int i = 1; i < A.length; i++) {
        sum[i] = sum[i-1] + A[i];
    }
    for (int i = 1; i < A.length-1; i++) {
        if (sum[i-1] == sum[A.length-1] - sum[i]) return i;
    }
    return -1;
}

文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/65171.html

相關文章

  • [HackerRank] Simple Array Sum | A Very Big Sum

    Simple Array Sum Problem Given an array of N integers, can you find the sum of its elements? Input Format The first line contains an integer, N, denoting the size of the array. The second line contain...

    harriszh 評論0 收藏0
  • [HackerRank] Diagonal Difference

    Problem Given a square matrix of size N x N, calculate the absolute difference between the sums of its diagonals. Input Format The first line contains a single integer, N. The next N lines denote the ...

    warmcheng 評論0 收藏0
  • [HackerRank] Plus Minus

    Problem Given an array of integers, calculate which fraction of its elements are positive, which fraction of its elements are negative, and which fraction of its elements are zeroes, respectively. Pri...

    leeon 評論0 收藏0
  • [HackerRank] Staircase

    Problem Your teacher has given you the task of drawing a staircase structure. Being an expert programmer, you decided to make a program to draw it for you instead. Given the required height, can you p...

    explorer_ddf 評論0 收藏0
  • [HackerRank] Time Conversion

    Problem Given a time in AM/PM format, convert it to military (24-hour) time. Input Format A single string containing a time in 12-hour clock format. Output Format Convert and print the given time in 2...

    longmon 評論0 收藏0

發(fā)表評論

0條評論

最新活動
閱讀需要支付1元查看
<