Java集合编程练习题
Java集合是Java编程中非常重要的一部分,它提供了一系列的数据结构和算法,方便我们存储和操作数据。本文将介绍一些常见的Java集合编程练习题,并提供相应的代码示例。
题目1:统计字符串中每个字符出现的次数
给定一个字符串,统计其中每个字符出现的次数,并打印出结果。例如,给定字符串 "hello world",输出结果为:
h: 1
e: 1
l: 3
o: 2
w: 1
r: 1
d: 1
解决这个问题的一种常见方法是使用HashMap来存储字符和对应的出现次数。我们可以遍历字符串,对于每个字符,如果它已经在HashMap中出现过,则将其出现次数加1;否则,在HashMap中添加该字符,并将出现次数初始化为1。
下面是解决这个问题的Java代码示例:
public class CharacterCount {
public static void main(String[] args) {
String str = "hello world";
HashMap<Character, Integer> charCountMap = new HashMap<>();
for (char c : str.toCharArray()) {
if (charCountMap.containsKey(c)) {
charCountMap.put(c, charCountMap.get(c) + 1);
} else {
charCountMap.put(c, 1);
}
}
for (Map.Entry<Character, Integer> entry : charCountMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
题目2:计算两个数组的交集
给定两个整数数组,编写一个函数来计算它们的交集。例如,给定数组 nums1 = [1,2,2,1],nums2 = [2,2],返回结果为 [2]。
解决这个问题的一种常见方法是使用HashSet来存储一个数组中的元素,然后遍历另一个数组,检查每个元素是否在HashSet中出现过。
下面是解决这个问题的Java代码示例:
public class Intersection {
public static int[] findIntersection(int[] nums1, int[] nums2) {
HashSet<Integer> set = new HashSet<>();
for (int num : nums1) {
set.add(num);
}
ArrayList<Integer> intersectionList = new ArrayList<>();
for (int num : nums2) {
if (set.contains(num)) {
intersectionList.add(num);
set.remove(num);
}
}
int[] intersection = new int[intersectionList.size()];
for (int i = 0; i < intersectionList.size(); i++) {
intersection[i] = intersectionList.get(i);
}
return intersection;
}
public static void main(String[] args) {
int[] nums1 = {1, 2, 2, 1};
int[] nums2 = {2, 2};
int[] intersection = findIntersection(nums1, nums2);
System.out.println(Arrays.toString(intersection));
}
}
题目3:计算数组中两个元素的最小差值
给定一个整数数组,编写一个函数来计算数组中两个元素的最小差值。例如,给定数组 [1, 5, 3, 9, 7],最小差值为2(元素为1和3)。
解决这个问题的一种常见方法是先对数组进行排序,然后遍历数组,计算相邻元素之间的差值,取最小值。
下面是解决这个问题的Java代码示例:
import java.util.Arrays;
public class MinDifference {
public static int findMinDifference(int[] nums) {
Arrays.sort(nums);
int minDifference = Integer.MAX_VALUE;
for (int i = 1; i < nums.length; i++) {
minDifference = Math.min(minDifference, nums[i] - nums[i - 1]);
}
return minDifference;
}
public static void main(String[] args) {
int[] nums = {1, 5, 3, 9, 7};
int minDifference = findMinDifference(nums);
System.out.println(minDifference);
}
}
在本文中,我们介绍了一些常见的Java集合编程练习题,并提供了相应的代码示例。这些练习题可以帮助您熟悉Java集合的使用方式