1. 给定两个整数数组nums1,nums2,找到它们的公共元素并返回。
将其中一个数组放入哈希表中,再遍历另一个数组进行判断即可。
可以通过布尔数组来实现一个哈希集合,在遍历nums1时,对于每个x,将hash[x]设为true。之后再对nums2进行遍历,对于nums2中的x,在hash[x]中进行对比,如果为真,将x存入结果中。
public class Solution
{
public ArrayList<Integer> intersection (ArrayList<Integer> nums1,
ArrayList<Integer> nums2)
{
boolean[] hash = new boolean[1010];
for(int x : nums1)
{
hash[x] = true;
}
ArrayList<Integer> ret = new ArrayList<>();
for(int x : nums2)
{
if(hash[x])
{
ret.add(x);
hash[x] = false;
}
}
return ret;
}
}
2. 请统计给定范围[L,R]的所有整数中,数字2的出现次数。如数字2出现一次2,数字22出现两次2。
此题主要考验如何统计数字2在一个数字中出现的次数。
对于一个数字判断它的若干位上是否有2,可以循环提取末位,然后再干掉末位。
public class Main
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int l = in.nextInt(), r = in.nextInt();
int ret = 0;
for(int i = l; i <= r; i++)
{
int tmp = i;
while(tmp != 0)
{
if(tmp % 10 == 2) ret++;
tmp /= 10;
}
}
System.out.println(ret);
}
}
3. 给定两个字符串str1和str2,再给定一个字符串数组strs,返回strs中str1和str2的最小距离,如果不存在str1或str2,或为null则返回-1。
用Pos1标记i位置之前最近一次出现str1的第一个字符串的下标,用Pos2标记i位置之前最近一次出现str2第一个字符串的下标。
在for循环中,接收每一个输入的strs成员,将每一个都与str1和str2比较,如果相等,将对应的i下标进行标记,再将两个标记Pos1和Pos2做差来找到新的最短距离。
public class Main
{
public static void main(String[] args) throws Throwable
{
BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));
int n = Integer.parseInt(reader.readLine());
String[] str = reader.readLine().split(" ");
String s1 = str[0], s2 = str[1];
int Pos1 = -1, Pos2 = -1, ret = 0x3f3f3f3f;
for(int i = 0; i < n; i++)
{
String s = reader.readLine();
if(s.equals(s1)) // 去前⾯找最近的 s2
{
if(Pos2 != -1)
{
ret = Math.min(ret, i - Pos2);
}
Pos1 = i;
}
else if(s.equals(s2)) // 去前⾯找最近的 s1 {
if(Pos1 != -1)
{
ret = Math.min(ret, i - Pos1);
}
Pos2 = i;
}
}
System.out.println(ret == 0x3f3f3f3f ? -1 : ret);
}
}
4. 牛牛拿到了一个字符串,他可以将其中相邻的两个相同字母进行消除,例如abbc可以变成ac,abba可以变成0,bbbbb可以变成b。
可以使用栈来模拟消除的过程
先创建一个字符数组,将字符串转化为字符数组。再创建一个StringBuilder来模拟栈,遍历字符数组,当栈为空并且上一个入栈元素与现在数组元素(即相邻的两个字母)不相同时,将数组字符进栈。如果栈不为空并且上一个入栈元素与现在数组元素(即相邻的两个字母)相同时,将上一个入栈元素删除,并且现在数组元素不入栈。最后遍历完成之后返回数组中的字母即可。
public class Main
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
char[] s = in.next().toCharArray();
StringBuilder st = new StringBuilder();
for(int i = 0; i < s.length; i++)
{
char ch = s[i];
if(st.length() != 0 && ch == st.charAt(st.length() - 1))
{
// 出栈
st.deleteCharAt(st.length() - 1);
}
else
{
// 进栈
st.append(ch);
}
}
System.out.println(st.length() == 0 ? 0 : st.toString());
}
}