第一题--------------------------------------------
def find_root(x):
while x!=parent[x]:
x=parent[x]
return x
def union(x,y):
x_root=find_root(x)
y_root=find_root(y)
parent[x_root]=y_root
n,m,p=map(int,input().strip().split())
parent=[i for i in range(n+1)]#初始化
for i in range(m):#h合并
tmp=list(map(int,input().strip().split()))
union(tmp[0],tmp[1])
for j in range(n):#判断
tmp=list(map(int,input().strip().split()))
if find_root(tmp[0])==find_root(tmp[1]):
print('Yes')
else:
print('No')
第二题--------------------------------------------------
class Solution {
int[] nums, tmp;
public int reversePairs(int[] nums) {
this.nums = nums;
// 辅助排序数组
tmp = new int[nums.length];
return mergeSort(0, nums.length - 1);
}
// 归并排序
private int mergeSort(int l, int r) {
// 终止条件
if (l >= r) return 0;
// 递归划分
int m = (l + r) / 2;
int res = mergeSort(l, m) + mergeSort(m + 1, r);
// 合并阶段
int i = l, j = m + 1;
for (int k = l; k <= r; k++)
tmp[k] = nums[k];
for (int k = l; k <= r; k++) {
if (i == m + 1)
nums[k] = tmp[j++];
else if (j == r + 1 || tmp[i] <= tmp[j])
nums[k] = tmp[i++];
else {
nums[k] = tmp[j++];
res += m - i + 1; // 统计逆序对
}
}
return res;
}
}
第三题-----------------------------------------
public class Solution {
public static int majorityElement(int[] nums) {
Set set = new HashSet();
int num;
int count = 0;
int result = 0;
for (int i = 0; i < nums.length; i++){
set.add(nums[i]);
}
Iterator it = set.iterator();
while (it.hasNext()){
count = 0;
num = (int) it.next();
for (int i = 0; i < nums.length; i++){
if (num == nums[i]){
count++;
}
if (count > Math.floor(nums.length/2)){
result = num;
}
}
}
return result;
}
public static void main(String[] args) {
int[] nums = new int[]{3,3,4};
int num = majorityElement(nums);
System.out.println(num);
}
}