简单版(1)
最大二进制奇数![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/3a71b2f417705f8d97a9d03b2a5090c8.png)
思路:计算1的个数为count,输出count-1个1,s长度-count个0,1
class Solution {
public:
string maximumOddBinaryNumber(string s) {
int cnt = count(s.begin(), s.end(), '1');
return string(cnt - 1, '1') + string(s.size() - cnt, '0') + '1';
}
};
作者:ylb
链接:https://leetcode.cn/problems/maximum-odd-binary-number/solutions/2683756/python3javacgotypescript-yi-ti-yi-jie-ta-aq52/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
两数之和
思路:JAVA中hashmap查找很快,可以用hashmap存储数组和他们的位置
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map=new HashMap<>();
for(int i=0;i<nums.length;i++){
if(map.containsKey(target-nums[i])){
return new int[] {map.get(target-nums[i]),i};
}
map.put(nums[i],i);
}
throw new IllegalArgumentException("No two sum solution");
}
}
回文数
思路:负数不是;0是;正数转换为字符串从0到n/2查看
class Solution {
public boolean isPalindrome(int x) {
int count=0;
if(x<0){
return false;
}
else if(x>=0&&x<10){
return true;
}
else{
String s=String.valueOf(x);
for(int i=0;i<s.length()/2;i++){
if(s.charAt(i)!=s.charAt(s.length()-i-1))
return false;
}
return true;
}
}
}
思路2: 数学方法,将数字分成左右两部分,如果两边相等则返回true
class Solution {
public boolean isPalindrome(int x) {
//思考:这里大家可以思考一下,为什么末尾为 0 就可以直接返回 false
if (x < 0 || (x % 10 == 0 && x != 0)) return false;
int revertedNumber = 0;
while (x > revertedNumber) {
revertedNumber = revertedNumber * 10 + x % 10;
x /= 10;
}
return x == revertedNumber || x == revertedNumber / 10;
}
}
作者:程序员吴师兄
链接:https://leetcode.cn/problems/palindrome-number/solutions/6170/dong-hua-hui-wen-shu-de-san-chong-jie-fa-fa-jie-ch/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
字母异位词分组
使用质数表示字母,则每个词相乘的数是唯一的,用哈希表保存所有的词,键值是相乘的数。`class Solution(object):
def groupAnagrams(self, strs):
“”"
:type strs: List[str]
:rtype: List[List[str]]
“”"
map = {‘a’: 2, ‘b’: 3, ‘c’: 5, ‘d’: 7, ‘e’: 11, ‘f’: 13, ‘g’: 17, ‘h’: 19, ‘i’: 23, ‘j’: 29, ‘k’: 31, ‘l’: 37, ‘m’: 41, ‘n’: 43, ‘o’: 47, ‘p’: 53, ‘q’: 59, ‘r’: 61, ‘s’: 67, ‘t’: 71, ‘u’: 73, ‘v’: 79, ‘w’: 83, ‘x’: 89, ‘y’: 97, ‘z’: 101}
#answer=List[strs];
remap={};
if len(strs)<=1: # 如果list是空
return [strs];
for s in strs:
temp=1;
for char in s:
temp*=map[char];
if temp not in remap:
remap[temp]=[s];
else:
remap[temp].append(s);
return list(remap.values());
`
最长连续序列
使用哈希列表查找,数的前一个和后一个是否在哈希表中,保存最长序列的个数。
class Solution(object):
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
temp1=set(nums);
max_length=0;
for key in temp1:
if key-1 not in temp1:
count_num=key;
count_length=1;
while count_num+1 in temp1:
count_num+=1;
count_length+=1;
max_length=max(count_length,max_length);
return max_length;
移动零
通过双指针,一个指向不是零序列的末端,一个遍历数组
class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
i=0;
for num in nums:
if num!=0:
nums[i]=num;
i+=1;
while i<len(nums):
nums[i]=0;
i+=1;
return nums;