陌陌2019秋招研发编程题题解

交换两个整型

题目描述

输入

输入待交换的两个整型数字,以空格分隔

输出

输出交换后的两个整型数字,以空格分隔

样例输入

1 2

样例输出

2 1

代码实现


package momo; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); Integer a = sc.nextInt(); Integer b = sc.nextInt(); a = a ^ b; b = a ^ b; a = a ^ b; System.out.println(a + " " + b); } }

字符串排列

题目描述

输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。

输入

输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。

输出

对应每组数据,按字典序输出所有排列。

样例输入

abc

样例输出

abc
acb
bac
bca
cab
cba

代码实现


package momo; import java.util.ArrayList; import java.util.Collections; import java.util.Scanner; public class Main2 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String str = sc.nextLine(); ArrayList<String> list = Permutation(str); for (String s : list) { System.out.println(s); } } public static ArrayList<String> Permutation(String str) { ArrayList<String> list = new ArrayList<>(); char[] ch = str.toCharArray(); Permu(ch, 0, list); Collections.sort(list); return list; } public static void Permu(char[] str, int i, ArrayList<String> list) { if (str == null) { return; } if (i == str.length - 1) { if (list.contains(String.valueOf(str))) { return; } list.add(String.valueOf(str)); } else { for (int j = i; j < str.length; j++) { char temp = str[j]; str[j] = str[i]; str[i] = temp; Permu(str, i + 1, list); temp = str[j]; str[j] = str[i]; str[i] = temp; } } } } 

最大乘积

题目描述

有长度为n的整数数组,从这 n 个整数中按照顺序选取m个,要求相邻两个整数在原数组中的位置相差不超过i,使得这 m 个整数的乘积最大,请返回最大乘积。
输入

第一行 整数n (1<n<20)
第二行 按顺序的n个整数   整数的范围在-50 到 50之间 
第三行 整数i和m  (1<i<20, 1<m<50)

输出

返回乘积

样例输入

3
7 4 7 
2 50

样例输出

49

代码实现


package momo; import java.util.Scanner; public class Main3 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); } int k = sc.nextInt(); int m = sc.nextInt(); long[][] maxProduct = new long[n][k]; long[][] minProduct = new long[n][k]; for (int i = 0; i < n; i++) { maxProduct[i][0] = arr[i]; minProduct[i][0] = arr[i]; } long max = Long.MIN_VALUE; for (int i = 0; i < n; i++) { for (int j = 1; j < k; j++) { for (int p = i - 1; p >= Math.max(i - m, 0); p--) { maxProduct[i][j] = Math.max(maxProduct[i][j], maxProduct[p][j - 1] * arr[i]); maxProduct[i][j] = Math.max(maxProduct[i][j], minProduct[p][j - 1] * arr[i]); minProduct[i][j] = Math.min(minProduct[i][j], minProduct[p][j - 1] * arr[i]); minProduct[i][j] = Math.min(minProduct[i][j], maxProduct[p][j - 1] * arr[i]); } } max = Math.max(max, maxProduct[i][k - 1]); } System.out.println(max); } }