Compare the Triplet hackerrank算法
有两个数组a [] = {a1,a2,a3} .b [] = {b1,b2,b3}比较两个数组的对应元素.a1> b1则a + 1 .a2 <b2,则b + 1.依次比较,大的一方加一。最后输出比较结果。
Sample Input 0
5 6 7
3 6 10
Sample Output 0
1 1
Sample Input 1
17 28 30
99 16 8
Sample Output 1
2 1
JAVA代码:
解决方案一:
public class Solution { // Complete the compareTriplets function below. static List<Integer> compareTriplets(List<Integer> a, List<Integer> b) { List<Integer> win = new LinkedList<Integer>(); int pointsAlice = ((a.get(0)>b.get(0))?1:0)+ ((a.get(1)>b.get(1))?1:0)+ ((a.get(2)>b.get(2))?1:0) ; int pointsBob = ((a.get(0)<b.get(0))?1:0)+ ((a.get(1)<b.get(1))?1:0)+ ((a.get(2)<b.get(2))?1:0) ; win.add(pointsAlice); win.add(pointsBob); return win; }
使用正则表达式简化代码
解决方案二:
static List<Integer> compareTriplets(List<Integer> a, List<Integer> b) { int aWin = 0; int bWin = 0; List<Integer> win = new LinkedList<Integer>(); for (int i = 0; i < a.size(); i++) { if (a.get(i) > b.get(i)) ++aWin; else if (a.get(i) < b.get(i)) ++bWin; } win.add(aWin); win.add(bWin); return win; }
for循环遍历对应的元素。
python3:
def compareTriplets(a, b): def compare_sum(tuple_): return sum([x > y for x, y in zip(*tuple_)]) return map( compare_sum, ((a, b), (b, a)) )