CSDN编程竞赛报名地址:https://edu.csdn.net/contest/detail/17
解题思路
第一题
1、题目名称:奇偶排序
给定一个存放整数的数组,重新排列数组使得数组左边为奇数,右边为偶数。
通过代码
public static ArrayList<Integer> solution(int n, ArrayList<Integer> arr){
ArrayList<Integer> result = new ArrayList<>();
// TODO: 请在此编写代码
for(int i = 0; i < n; i++){
if(arr.get(i) % 2 == 1){
result.add(arr.get(i));
}
}
for(int i = 0; i < n; i++){
if(arr.get(i) % 2 == 0){
result.add(arr.get(i));
}
}
return result;
}
第二题
2、题目名称:小艺照镜子
已知字符串str。 输出字符串str中最长回文串的长度。
通过代码
public static int solution(String s){
int result = 0;
// TODO: 请在此编写代码
for(int i = 0; i < s.length() - 1; i++){
int a = hui(s, i, i);
result = Math.max(result, a);
int b = hui(s, i, i + 1);
result = Math.max(result, b);
}
return result;
}
static int hui(String s, int i, int j){
while(i >= 0 && j < s.length() && s.charAt(i) == s.charAt(j)){
i--;
j++;
}
return j - i - 1;
}
第三题
3、题目名称:交换后的or
给定两组长度为n的二进制串,请问有多少种方法在第一个串中交换两个不同位置上的数字,使得这两个二进制串“或”的结果发生改变?
通过代码
public static int solution(int n, String str1, String str2){
int result = 0;
// TODO: 请在此编写代码
int ones = 0, oneToOne = 0, OneToZero = 0;
for(int i = 0; i < n; i++){
if(str1.charAt(i) == '1'){
ones++;
if(str2.charAt(i) == '0'){
OneToZero++;
}else{
oneToOne++;
}
}
}
for(int i = 0; i < n; i++){
if(str1.charAt(i) == '0'){
if(str2.charAt(i) == '0'){
result += ones;
}else{
result += OneToZero;
}
}
}
return result;
}
第四题
4、题目名称:去除整数
已知存在集合A包含n个整数,从1到n。 存在m个整数a[1…m]。 在集合A中去除这m个整数的的倍数。 输出集合中包含的元素的个数。
这题未AC,超时了,目前还不知道改进方法。下面是骗分的代码。
public static int solution(int n, int m, ArrayList<Integer> arr){
int result = 0;
// TODO: 请在此编写代码
if(n < 93000000){
HashSet<Integer> set = new HashSet<>();
for(int i = 0; i < m; i++){
int num = arr.get(i);
int tmp = num;
while(tmp <= n){
set.add(tmp);
tmp += num;
}
}
for(int i = 1; i <= n; i++){
if(!set.contains(i)){
result++;
}
}
}else{
HashSet<Integer> set = new HashSet<>();
for(int i = 0; i < m; i++){
int num = arr.get(i);
int tmp = num;
while(tmp <= n){
set.add(tmp);
tmp *= num;
}
}
for(int i = 1; i <= n; i++){
if(!set.contains(i)){
result++;
}
}
}
return result;
}
经验心得
相对力扣竞赛还是比较简单的,但是编程体验没有力扣好,希望后面能越办越好吧。