LeetCode之数组处理题java
342. Power of Four
Given an integer (signed 32 bits), write a function to check whether it is a power of 4.
Example:
Given num = 16, return true.
Given num = 5, return false.
public class Solution {
public boolean isPowerOfFour(int num) {
if(num==0)
return false;
while(num%4==0){
num = num>>2;
}
if(num==1)
return true;
return false;
}
}
326. Power of Three
Given an integer, write a function to determine if it is a power of three.
Follow up:
Could you do it without using any loop / recursion?
public class Solution {
public boolean isPowerOfThree(int num) {
if(num==0)
return false;
while(num%3==0){
num = num/3;
}
if(num==1)
return true;
return false;
}
}
231. Power of Two
Given an integer, write a function to determine if it is a power of two.
public class Solution {
public boolean isPowerOfTwo(int n) {
if(n==0)
return false;
while(n%2==0){
n = n>>1;
}
if(n==1)
return true;
return false;
}
}
349. Intersection of Two Arrays
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
Note:
- Each element in the result must be unique.
- The result can be in any order.
思路:使用一个BitSet集合存放一个数组数据,之后再用另一个数组与其比较,把集合中有的数据放入返回的数组中
import java.util.Arrays;
import java.util.BitSet; public class Solution { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int nums1[] = {1,2,3,2,4,2,5,2};
int nums2[] = {2,3,5,6};
int num[] = intersection(nums1, nums2);
for(int i=0;i<num.length;i++){
System.out.print(num[i]+" ");
}
} public static int[] intersection(int[] nums1, int[] nums2) {
if(nums1.length==0||nums2.length==0)
return new int[0];
int len1 = nums1.length;
int len2 = nums2.length;
int[] result = new int[Math.min(len1, len2)];
BitSet set = new BitSet();
for(int i=0;i<len1;i++){
set.set(nums1[i]);
}
int k = 0;
for(int j=0;j<len2;j++){
if(set.get(nums2[j])){
result[k++] = nums2[j];
set.set(nums2[j], false);
}
}
return Arrays.copyOfRange(result, 0, k);
} }
349. Intersection of Two Arrays
Given two arrays, write a function to compute their intersection.
Example:
Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].
思路:使用hashset去重nums1,在对nums2去重时,同时过滤nums1中的数
import java.util.*;
public class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set = new HashSet<Integer>();
Set<Integer> insect = new HashSet<Integer>();
for(int i=0;i<nums1.length;i++){
set.add(nums1[i]);
}
for(int i=0;i<nums2.length;i++){
if(set.contains(nums2[i])){
insect.add(nums2[i]);
}
}
int[] res = new int[insect.size()];
int i=0;
for(Integer num : insect){
res[i++] = num;
}
return res;
}
}
137. Single Number II
Given an array of integers, every element appears three times except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
思路:先排序
1)当只有一个数时,直接return;
2)当刚好四个数时,两种情况-->第一个数或最后一个数;
3)>4个数时,三种情况:a.第一个数;b.最后一个数;c.循环中部查找;
public class Solution {
public int singleNumber(int[] nums) {
Arrays.sort(nums);
if(nums.length==1)
return nums[0];
if(nums.length==4){
if(nums[0]==nums[1]){
return nums[3];
}else{
return nums[0];
}
}
if(nums[0]!=nums[1])
return nums[0];
if(nums[nums.length-1]!=nums[nums.length-2])
return nums[nums.length-1];
for(int i=1;i<nums.length-1;i++){
if(nums[i]!=nums[i-1]&&nums[i]!=nums[i+1]){
return nums[i];
}
}
return -1;
}
}
260. Single Number III
Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.
For example:
Given nums = [1, 2, 1, 3, 2, 5], return [3, 5].
Note:
- The order of the result is not important. So in the above example,
[5, 3]is also correct. - Your algorithm should run in linear runtime complexity. Could you implement it using only constant space complexity?
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.
思路1(笨办法):1)考虑数组为空,则直接返回-1;
2)数组只有一个时,则返回该数;
3)其他,先排序,再将数组长度切成两半:n/2,再循环判断i对应的数是否等于n/2+i所对应的数,如果存在,则直接返回nums[i],否则返回-1;
public class Solution {
public int majorityElement(int[] nums) {
if(nums.length==0||nums==null)
return -1;
Arrays.sort(nums);
int len = nums.length;
for(int i=0;i<len-len/2;i++){
if(nums[i]==nums[len/2+i]){
return nums[i];
}
}
return -1;
}
}
思路2:1)隐含:数组中有一个数字出现的次数超过了数组长度的一半,则如果对数组进行排序,那么排序后位于数组中间的数字一定就是那个出现次数超过数组长度一般的数字;
2)使用快排的partition函数来辅助,如果partition函数返回的index>middle,则中位在左边,若index<middle,则中位在右边;
3)最后统计middle所对应的数出现的次数是否超过一半,超过则返回,否则返回-1;
思路3:数组中有一个数字出现的次数超过数组的一半,则该数出现的次数超过其他数字出现的次数;因此遍历数组时,保存两个值:一个是数组中的一个数字,一个是次数;
1)当我们遍历到下一个数字时,如果下一次遍历的数字与保存的数字相同,则次数加1,否则次数减1,当次数减为0时,保存下一个数字;
public class Solution {
public int majorityElement(int[] nums) {
if(nums==null||nums.length==0)
return -1;
int number = nums[0];
int count = 1;
for(int i=1;i<nums.length;i++){
if(count==0){
number = nums[i];
count = 1;
}else if(nums[i]==number){
count++;
}else{
count--;
}
}
return number;
}
}
229. Majority Element II
Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. The algorithm should run in linear time and in O(1) space.
217. Contains Duplicate
Given an array of integers, find if the array contains any duplicates. Your function should return true if any value appears at least twice in the array, and it should return false if every element is distinct.
思路:1)考虑数组为空时,return false;
2)考虑数组长度为1或0时,return false;
3)将数组进行排序,再比较相邻的两个数,如果相等,则return true,否则return fasle;
public class Solution {
public boolean containsDuplicate(int[] nums) {
if(nums==null||nums.length<=1)
return false;
Arrays.sort(nums);
for(int i=1;i<nums.length;i++){
if(nums[i-1]==nums[i]){
return true;
}
}
return false;
}
}
219. Contains Duplicate II
Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j]and the difference between i and j is at most k.
202. Happy Number
Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.
Example: 19 is a happy number

思路:使用一个HashSet来保存每一次平方和的结果,如果HashSet添加时有相同的数时,直接返回false(因为进入了死循环),直到结果为1结束,返回true。
public static boolean isHappy(int n){
if(n==0)
return false;
HashSet<Integer> set = new HashSet<Integer>();
while(n!=1){
n = sumOfSquar(n);
if(!set.add(n)){
return false;
}
set.add(n);
}
return true;
}
// public static boolean isHappy(int n) {
// if(n==0)
// return false;
//
// while(n!=1&&n!=4){
// n = sumOfSquar(n);
// }
// return (n==1)?true:false;
// }
public static int sumOfSquar(int n){
int m = 0;
int sum = 0;
while(n!=0){
m = (n%10);
sum += m*m;
n = n/10;
}
return sum;
}
LeetCode之数组处理题java的更多相关文章
- LeetCode第[21][23]题(Java):Merge Sorted Lists
题目:合并两个已排序链表 难度:Easy 题目内容: Merge two sorted linked lists and return it as a new list. The new list s ...
- LeetCode之字符串处理题java
344. Reverse String Write a function that takes a string as input and returns the string reversed. E ...
- LeetCode之二叉树作题java
100. Same Tree Total Accepted: 127501 Total Submissions: 294584 Difficulty: Easy Given two binary tr ...
- LeetCode第[18]题(Java):4Sum 标签:Array
题目难度:Medium 题目: Given an array S of n integers, are there elements a, b, c, and d in S such that a + ...
- LeetCode第[1]题(Java):Two Sum 标签:Array
题目: Given an array of integers, return indices of the two numbers such that they add up to a specifi ...
- LeetCode第[46]题(Java):Permutations(求所有全排列) 含扩展——第[47]题Permutations 2
题目:求所有全排列 难度:Medium 题目内容: Given a collection of distinct integers, return all possible permutations. ...
- LeetCode第[1]题(Java):Two Sum (俩数和为目标数的下标)——EASY
题目: Given an array of integers, return indices of the two numbers such that they add up to a specifi ...
- LeetCode第[29]题(Java):Divide Two Integers
题目:两整数相除 难度:Medium 题目内容: Given two integers dividend and divisor, divide two integers without using ...
- LeetCode面试常见100题( TOP 100 Liked Questions)
LeetCode面试常见100题( TOP 100 Liked Questions) 置顶 2018年07月16日 11:25:22 lanyu_01 阅读数 9704更多 分类专栏: 面试编程题真题 ...
随机推荐
- UWP 流畅设计中的光照效果(容易的 RevealBorderBrush 和不那么容易的 RevealBackgroundBrush)
在 Windows 10.0.16299 中,RevealBrush 被引入,可以实现炫酷的鼠标滑过高亮效果和点击光照.本文将告诉大家如何完整地实现这样的效果. Reveal 的效果(自带) 在微软官 ...
- vmware linux nat模式设置静态ip
网上资料很多,但是都不怎么实用,这里给大家总结一下.nat模式上网.因为nat本身就能上网为什么还要设置ip.这有点自找麻烦.但是在集群这是必须的.要么你搭建伪分布,要么至少具有三台物理机器.为了节省 ...
- L2-017. 人以群分
社交网络中我们给每个人定义了一个“活跃度”,现希望根据这个指标把人群分为两大类,即外向型(outgoing,即活跃度高的)和内向型(introverted,即活跃度低的).要求两类人群的规模尽可能接近 ...
- IO流-文件夹的拷贝
文件夹的拷贝操作 要求: 完成文件夹的拷贝,包括子目录的拷贝和所有文件的拷贝 分析: 首先,得在目标目录下创建一个与源文件夹名称相同的文件夹 遍历源文件夹中的所有文件对象,判断子文件是目录还是文件 如 ...
- grpc rust 项目基本使用
1. 安装依赖(rust 基本依赖就不说了,需要配置环境变量) protoc 参考: https://github.com/google/protobuf/releases/tag/v3.5.1 2. ...
- ZooKeeper+Kafka+Storm
http://www.cnblogs.com/panfeng412/archive/2012/11/30/how-to-install-and-deploy-storm-cluster.html
- BOM的编制与管理
Bill of Material BOM英文全称 Bill of Material,即“物料清单”,也称产品结构表.在制造业管理信息系统中,经常会提到BOM.物料清单是指产品所需零部件明细表及其结构. ...
- 设计WEB数据库(学习)
设计WEB数据库 1.考虑建模的实际对象 为现实世界的实体和关系建立模型 在上面情况下考虑建表呢? 答:如果有一组属于同一类型的数据,就可以根据这些数据创建表 2.避免保存冗余数据 原因:a.空间的浪 ...
- mqtt 异步消息 长连接 解析
mqtt 是轻量级基于代理的发布/订阅的消息传输协议,设计思想是开放,简单,轻量级,且易于实现,这些优点使得他受用于任何环境 该协议的特点有: 使用发布/订阅消息的模式,提供一对多的消息发布,解除应用 ...
- Java 8Lambda之方法引用(Method References)
方法引用分为4类,方法引用也受到访问控制权限的限制,可以通过在引用位置是否能够调用被引用方法来判断.具体分类信息如下: 类型 使用方式 静态方法 ContainingClass::staticMeth ...