Given an array containing n distinct numbers taken from 0, 1, 2, …, n, find the one that is missing from the array.
For example,
Given nums = [0, 1, 3] return 2.
这题很简单,不过有个坑爹的地方,就是给你[1,0]的时候,你也要返回2
数组中都是从0到n的数字,和数组的下标刚好吻合嘛,假设缺少数字n(n在数组中),数组长度m=nums.length();
数组里的元素就是 0 1 2 3 ··· n-1 n+1 n+2··· m (1)
数组中的下标就是 0 1 2 3 ··· n-1 n n+1··· m-1 (2)
(2)-(1)=n-m
那么再+m,就得到了我们要求的n!而如果像[1,0]这种情况,那么只要返回数组长度值即可也就是m。
于是代码为:
public class Solution {
public int missingNumber(int[] nums) {
int result=nums.length;
for(int i=0;i<nums.length;i++){
result+=i-nums[i];
}
return result;
}
}
Given a string array words, find the maximum value of length(word[i]) * length(word[j]) where the two words do not share common letters. You may assume that each word will contain only lower case letters. If no such two words exist, return 0.
Example 1:
Given [“abcw”, “baz”, “foo”, “bar”, “xtfn”, “abcdef”]
Return 16
The two words can be “abcw”, “xtfn”.
Example 2:
Given [“a”, “ab”, “abc”, “d”, “cd”, “bcd”, “abcd”]
Return 4
The two words can be “ab”, “cd”.
Example 3:
Given [“a”, “aa”, “aaa”, “aaaa”]
Return 0
No such pair of words.
这道题目开始时是没有头绪的,但是看到在bit manipulation中,就在想如何和位操作关联呢?看到了别人代码的开头创建了一个数组,我瞬间就懂了思路了。
大体如下
a 1
b 10
c 100
ac 101
abc 111
就是这种意思~~!每个字母的顺序代表了它在第几个bit位
于是,我们就可以把每个字符串换成一个二进制数,再通过相与来判断是否有相同的位,有,那便代表有重复了的字母,没有就计算两个长度的乘积,找到最大值!
代码奉上:
public class Solution {
public int maxProduct(String[] words) {
//max的默认值为0
int max=0,i,j;
//创建一个数组来记录每个字符串所代表的二进制数
int[] b=new int[words.length];
for(i=0;i<words.length;i++){
int result=0;
for(j=0;j<words[i].length();j++){
result|=1<<(words[i].charAt(j)-'a');
}
b[i]=result;
}
for(i=0;i<b.length;i++){
for(j=i+1;j<b.length;j++){
if((b[i]&b[j])==0){//相与为0表示没有相同字母
//返回最大值
max=Math.max(max,(words[i].length())*(words[j].length()));
}
}
}
return max;
}
}