剑指 Offer 50. 第一个只出现一次的字符
方法一:哈希表
class Solution {
public char firstUniqChar(String s) {
HashMap<Character,Integer> map=new HashMap<>();
for(int i=0;i<s.length();i++){
char c=s.charAt(i);
map.put(c,map.getOrDefault(c,0)+1);
}
char res=' ';
for(int i=0;i<s.length();i++){
if(map.get(s.charAt(i))==1){
res=s.charAt(i);
break;
}
}
return res;
}
}
方法二:字典查找
class Solution {
public char firstUniqChar(String s) {
char res=' ';
int[] num=new int[26];
for(int i=0;i<s.length();i++){
num[s.charAt(i)-'a']++;
}
for(int i=0;i<s.length();i++){
if(num[s.charAt(i)-'a']==1){
res=s.charAt(i);
break;
}
}
return res;
}
}
剑指 Offer 53 - I. 在排序数组中查找数字 I
class Solution {
public int search(int[] nums, int target) {
int count=0;
int flag=0;
for(int i=0;i<nums.length;i++){
if(nums[i]==target){
flag=1;
count++;
}else{
if(flag==1) break;
}
}
return count;
}
}