347. Top K Frequent Elements
Given a non-empty array of integers, return the k most frequent elements.
For example,
Given [1,1,1,2,2,3]
and k = 2, return [1,2]
.
Note:
- You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
- Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Solution {
public List<Integer> topKFrequent(int[] nums, int k) {
List<Integer> l = new ArrayList<Integer>(k);
if(nums.length==k)
{
for(int i=0;i<k;i++)
l.add(nums[i]);
return l;
}
Arrays.sort(nums);
for(int i=0;i<k;i++){
int last = nums[0], lastindex = 0,max = 0,maxnum = nums[0];
for(int j=1;j<nums.length;j++){
if(nums[j]!=last){
if(j-lastindex>max && !l.contains(nums[j-1])){
max = j-lastindex;
maxnum = nums[j-1];
}
last = nums[j];
lastindex = j;
}
if(j==nums.length-1){
if (j-lastindex+1 > max && !l.contains(nums[j])){
maxnum = nums[j];
}
}
}
l.add(maxnum);
}
return l;
}
}
169. Majority Element
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋
times.
You may assume that the array is non-empty and the majority element always exist in the array.
思路:这道题,我排序以后,逐个元素检查,一旦发现和前面一个不一样的,我就计算前面那个出现了多少次,出现的次数如果>n/2,那么就直接break输出。如果到最后都没输出,那么就是最后一个元素输出。其实可以优化一下,就是一旦index>n/2还没输出,那就直接输出最后一个元素。。
public class Solution {
public int majorityElement(int[] nums) {
Arrays.sort(nums);
int lastindex = 0;
int ele = nums[0];
for(int i=1;i<nums.length;i++){
if(nums[i]!=nums[i-1])
{
if(i-lastindex>nums.length/2)
{
ele = nums[i-1];
return ele;
}
lastindex = i;
}
}
return nums[nums.length-1];
}
}
看看别人的程序,O(n),=-=好像跟前面某些题目有些相近,怎么想出来的啊。。
public class Solution {
public int majorityElement(int[] nums) {
int maj = nums[0];
int cc = 1;
for(int i=1; i<nums.length; i++) {
if(nums[i] == maj) {
cc++;
}
else {
cc--;
if(cc == 0) {
maj = nums[i];
cc = 1;
}
}
}
return maj;
}
}
357. Count Numbers with Unique Digits
Given a non-negative integer n, count all numbers with unique digits, x, where 0 ≤ x < 10n.
Example:
Given n = 2, return 91. (The answer should be the total numbers in the range of 0 ≤ x < 100, excluding [11,22,33,44,55,66,77,88,99]
)
public class Solution {
public int countNumbersWithUniqueDigits(int n) {
int[] count = new int[11];
count[0] = 1;count[1] = 10;
for(int i=2;i<=10;i++){
count[i] = 9;
for(int k=9; k>10-i ;k--)
count[i]*=k;
count[i] = count[i] +count[i-1];
}
return n>10?count[10]:count[n];
}
}