剑指offer专项突击版 ---- 第2天
作者:互联网
class Solution {
public int singleNumber(int[] nums) {
int ans = 0;
for(int i = 0; i < 32; i++){
int target = 0;
for(int num : nums){
target += (num >> i) & 1;
}
ans |= (target%3) << i;
}
return ans;
}
}
class Solution{
// 暴力解法
// m 表示单词的平均长度,n 表示单词的个数
// 时间复杂度:O(n^2 * m)
// 空间复杂度:O(1)
public int maxProduct(String[] words) {
int ans = 0;
for (int i = 0; i < words.length -1; i++) {
String word1 = words[i];
for (int j = i + 1; j < words.length; j++) {
String word2 = words[j];
// 每个单词的 bitMask 会重复计算很多次
if (!hasSameChar(word1, word2)) {
ans = Math.max(ans, word1.length() * word2.length());
}
}
}
return ans;
}
// O(m^2)
private boolean hasSameChar(String word1, String word2) {
for (char c : word1.toCharArray()) {
if (word2.indexOf(c) != -1) return true;
}
return false;
}
}
class Solution {
// 时间复杂度:O(n)
// 空间复杂度:O(1)
public int[] twoSum(int[] nums, int target) {
if (nums == null || nums.length == 0) return new int[0];
int left = 0;
int right = nums.length - 1;
while (left < right) {
int sum = nums[left] + nums[right];
if (sum == target) {
return new int[]{left, right};
} else if (sum < target) {
left++;
} else {
right--;
}
}
return new int[0];
}
}
标签:专项,right,return,nums,int,offer,----,length,ans 来源: https://blog.csdn.net/DUANJIAWEIDUANJIAWEI/article/details/122135231