声明:本人只是按照题目编写出解题程序,并未考虑算法的效率,不足的地方望大家指正,有更好的解题思路,欢迎评论。
1、卖水果
题目:输入购买次数n和每次购买的水果,求卖出苹果的次数?
例:
n=1 apple orange banana
n=2 apple orange
n=3 orange
例子中,每次购买的水中加入到string数组中,
String[1] = "apple orange banana";
String[2] = "apple orange";
String[3] = "orange";
输出:apple 2
public static void f1(int n, String[] str) {
int count = 0;
for (int i = 0; i < str.length; i++) {
if (str[i].toCharArray().length > 5) {
String[] split = str[i].split(" ");
for (int j = 0; j < split.length; j++) {
if (split[j].equals("apple")) {
count++;
}
}
}
if (str[i].equals("apple")) {
count++;
}
}
System.out.println("apple " +count);
}
2、合并数列输出
题目:输入int x,int y,int[x]nums1,int[y]nums2
x和y分别表示,nuns1和nums2的长度
如:x=3 y = 4
nums1 = [1,2,3];
nums2=[3,4,5,2];
输出:1,3,4,5
如:x=2 y = 2
nums1 = [7,5];
nums2=[3,4];
输出:3,4,5,7
public static void f2(int x, int y, int[] arr1, int[] arr2) {
int[] s = new int[x + y-1];
for (int i = 0; i < x; i++) {
s[i] = arr1[i];
}
for (int j = 0; j < y-1; j++) {
s[x + j] = arr2[j];
}
Arrays.sort(s);
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int val : s) {
Integer count = map.get(val);
if (map.containsKey(val)) {
map.put(val, count + 1);
} else {
map.put(val, 1);
}
}
for(int key:map.keySet()){
if(map.get(key)==1){
System.out.println(key);
}
}
}