Anagram 拆分数组 看一半操作几次能成为另一半的anagram

题目

输入第一行是要判断的字符串的个数n,之后的n行输入为需要判断的字符串。

每个字符串str,是两个等长字符串的合体,所以长度一定是偶数。若为奇数,返回-1。

所以str分成两个substring,右边需要多少次操作能变为左边。只要用一个26位的数组统计每个字符在a和b中出现的次数就行,在a中出现+1,在b中出现-1,最后统计数组的26位元素的绝对值除以2,就是要进行操作的次数。

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 数组中重复元素的个数

题目

找到一个数组中重复元素的个数。

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;

}

或者用数组

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个人投票,名字(票数)最多的获胜,若票数相同,名字字母顺序靠后的获胜。

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 数组里取x,y 看pow(x,y)奇偶性

题目

其实就是给一个数组,然后给一些index pair,看数组中对应index的两个数的pow(x, y)是奇数还是偶数。

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\n");

else sb.append("Even\n");

}

System.out.print(sb);

}

}

The Bit Game 在某区间内最大的两数XOR值

题目

在l和r之间取两个数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在本次循环起始的位置,谁知道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 每次按最短那根的长度切所有木头,每次切完记录剩余的木头数

题目

有N条木段,每次切割必须这样:把所有的木段都切掉最短的那条木段的长度。每次切割后记录剩余木段的条数,最短的木段肯定没了嘛,如此重复,直到都被切秃噜了(为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? 判断质数 返回最大因数

题目

是质数,返回1;不是质数,返回最大因数。

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 约分 约分

解法

找最大公约数,分子和分母都除以公约数后加入StringBuilder,再添加到结果数组即可。

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

....

题目

给出层数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 给小孩发糖果 令分配公平不悬殊

题目

N包糖,里面的糖果数不同,挑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.

题目

循环执行转弯、前进的一串动作,能否回到原点?告诉你,只和角度有关。一个L,就是90°,再来一个R,就把它抵消了,那就回不去了。最后剩下的L为奇数个,就回得去。

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。

循环,每个齿轮,找合适的另一个齿轮分两步:先找到符合尺寸标准的所有齿轮,再从这些齿轮中找到造价最低的那个,将index加入结果数组。

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

题目

不断给某个区间做加同一个数的操作,问最后最大的数变成了多少。

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 找一个数的补码

找到最高位,建立掩码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的每一个句子是一个字符串,我们要计算将这些字符串转变为回文字符串的操作次数。

例如a-->c,要走两次哦。那么"abc"的步数就是2,"abcd"的步数就是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); //统计浪费的零头

}

int profit = sumOfLengths*metal_price - sumOfCutCounts*cost_per_cut - sumOfCutWastes*metal_price; //总价 - 切割费用 - 浪费材料价值

if (profit > maxProfit) {

maxProfit = profit; //更新最大利润

}

}

return maxProfit;

}

#Gem Stones 有几个字符在所有字符串都出现了呢

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的数,只能是右子树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;i

int x = s.charAt(i)-'A', y = s.charAt(i+2)-'A';

if(graph[x][y]) //duplicate edge

E2 = true;

graph[x][y] = true;

nodes.add(s.charAt(i));

nodes.add(s.charAt(i+2));

}

//check error E1: more than 2 children

boolean E1 = false;

for(int i=0;i<26;i++){

int count = 0; //number of child

for(int j=0;j<26;j++){

if(graph[i][j])

count++;

}

if(count>2)

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

int j = i+1;

while(a[j]-a[i] < k) {

j++;

if(j==n) break;

}

if (j == n) continue;

if(a[j]-a[i]==k) count++;

}

return count;

}

#Maximum Difference in an Array -- Nice

数组中任意两元素的最大差值,必须是后面的减前面的。

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;

}

java单链表选票_Hackerrank Practice相关推荐

  1. java单链表选票_200个经典C程序源码

    经典的C资源,很全面详细 对于初学者来说,太重要了! 包含以下内容:第一部分 基础篇 001 第一个C程序 002 运行多个源文件 003 求整数之积 004 比较实数大小 005 字符的输出 006 ...

  2. Java单链表反转 详细过程

    Java单链表反转 Java实现单链表翻转     [尊重原创,转载请注明出处]http://blog.csdn.net/guyuealian/article/details/51119499 (一) ...

  3. Java单链表、双端链表、有序链表实现

    Java单链表.双端链表.有序链表实现 原创 2014年03月31日 23:45:35 标签: Java / 单链表 / 双端链表 / 有序链表 65040 单链表: insertFirst:在表头插 ...

  4. java单链表输出_数据结构基础------1.线性表之单链表的创建与输出方法(Java版)...

    基础知识: 线性表(linear list),是其组成元素间具有线性关系的一种线性结构. 线性表有 ①顺序存储结构(sequential storage structure) 顺序存储结构可以简单的理 ...

  5. java单链表例子_写一个java链表的例子?随便举例说一下。

    展开全部 //单链表类 package dataStructure.linearList; import dataStructure.linearList.Node; //导入单链表结点类 impor ...

  6. java链式结构_(Java)单链表Java语言链式结构实现(数据结构四)

    1.迭代器接口实现 package com.zhaochao; public interface Iterator { boolean hasNext(); E next(); boolean del ...

  7. java单链表查询功能,Java 实现简答的单链表的功能

    作者:林子木  博客网址:http://blog.csdn.net/wolinxuebin 參考网址:http://blog.csdn.net/sunsaigang/article/details/5 ...

  8. java单链表节点翻转_Java数据结构01-链表基础(讲解+代码+面试题)

    文章结构 链表的概念/用处 链表的基本代码实现(韩顺平Java数据结构网课) 剑指offer上链表题目代码实现(个人手敲,更精巧的答案可以参考官网) 链表 链表包含单链表,双向链表,循环链表等等.相对 ...

  9. java单链表_(java实现)单链表

    什么是单链表 在了解单链表之前,你知道什么是链表吗?如果你不知道什么是链表,可以看看我的这篇博客 单链表是链表的其中一种基本结构.一个最简单的结点结构如图所示,它是构成单链表的基本结点结构.在结点中数 ...

最新文章

  1. graphql_普通英语GraphQL指南
  2. 【青少年编程】【三级】加法出题机
  3. 英伟达小姐姐的Python隐藏技巧合集,推特2400赞,代码可以直接跑
  4. 计算机/ARM 系统
  5. shell编程-条件判断
  6. 配置mysql-cluster群集高可用(三)
  7. [MATLAB学习笔记]clf清空图窗1013(1)
  8. leetcode-1-两数之和
  9. 排列、组合问题(递归)
  10. 工作笔记-SDRAM的读写
  11. Delta3d动态角色层
  12. 软著文档鉴别材料_软著申请被驳回补正材料期限是多久?逾期未补正申请被撤回怎么办?...
  13. 一个咸鱼的python_一个咸鱼的Python爬虫之路(三):爬取网页图片
  14. matlab实现匹配滤波器实验报告,匹配滤波器的仿真实验报告
  15. 北京地区广播电台频率
  16. Ubuntu——笔记本插入耳机没有声音的解决方案
  17. 关于微信小程序的navigator标签
  18. 专科计算机专业软件工程,软件工程专业专科学校都有哪些?
  19. 【Luogu P1488】【博弈论】 肥猫的游戏
  20. renren_login_urllib

热门文章

  1. PHP四种基本排序算法
  2. 擠出機步進馬達的 Steps per Unit 該如何計算?
  3. Qt connect parent widget 连接父控件的信号槽
  4. poj2125最小点权覆盖
  5. Revit二次开发示例:AutoUpdate
  6. sql server 左右连接 内外连接
  7. Linux meson + ninja编译安装源码(八)
  8. Mac使用010editor
  9. python内置函数__init__及__str__的区别
  10. Android 关机流程 从kernel到framework