写在开头:正值毕业生求职期间,翻一翻剑指offer的书籍,将其中的题目进行分析和代码编写,并将代码整理到csdn博客上,如果有错误,敬请指出!(此系列不提供题目原文,请参考书籍《剑指offer第二版》即可。)
Test60 - Test66系列
1. Test61.java
import java.util.Arrays;
public class Test61{
public static void isContinuous(int[] num)
{
if(num==null||num.length<1)
return false;
Arrays.sort(num);
int numzero = 0;
int numgap = 0;
for(int i=0;i<num.length;i++)
{
if(num[i]==0)
numzero++;
}
int small = numzero;
int big = small+1;
while(big<=num.length-1)
{
if(num[small]==num[big])
return false;
numgap += num[big]-num[small]-1;
small = big;
big++;
}
if(numzero>=numgap)
return true;
else
return false;
}
}
2. Test62.java
import java.util.LinkedList;
public class Test62{
public static int circlelastone(int n,int m) {
if (n < 1 || m < 1)
return -1;
LinkedList<Integer> list = new LinkedList<Integer>();
for (int i = 0; i < n; i++) {
list.add(i);
}
int index = 0;
while(list.size() > 1)
{
for(int i=1; i<m;i++)
{
index = (index+1)%list.size();
}
int k =list.remove(index);
System.out.println(index);
System.out.println(k);
}
return list.get(0);
}
public static void main(String[] args)
{
int n=5;
int m=3;
System.out.println(circlelastone(n,m));
}
}
3. Test63.java
public class Test63{
public static int maxprofit(int[] data)
{
if(data==null||data.length<1)
return -1;
int min = data[0];
int maxsiff = data[1]-min;
if(data[1]<min)
min=data[1];
for(int i=2;i<data.length;i++)
{
if(data[i]-min>maxsiff)
maxsiff=data[i]-min;
if(data[i]<min)
min=data[i];
}
return maxsiff;
}
public static void main(String[] args)
{
int[] data ={9,11,8,5,7,12,18,19};
System.out.println(maxprofit(data));
}
}
4. Test64.java
public class Test64{
static int sum =0;
static int i=1;
public static int sum(int n)
{
if(n<0)
return -1;
if(i<=n) {
sum += i;
i++;
sum(n);
}
return sum;
}
public static void main(String[] args)
{
System.out.println(sum(6));
}
}
5. Test65.java
public class Test65{
public static int sum(int num1,int num2)
{
int s = 0;
int carry =0;
do{
s = num1^num2;
carry =(num1&num2)<<1;
num1 = s;
num2 = carry;
}while(carry!=0)
return s;
}
}
6. Test66.java
public class Test66{
public static int[] getmultiplyarray(int[] a)
{
if(a==null||a.length<1)
return null;
int[] b = new int[a.length];
int[] c = new int[a.length];
c[0]==1;
int[] d = new int[a.length];
d[a.length-1]=1;
for(int i=1;i<a.length;i++) {
c[i] = c[i - 1];
for (int j = i; j > i - 1; j--) {
c[i] *= a[j - 1];
}
}
for(int i=a.length-2;i>=0;i--)
{
d[i]=d[i+1];
for(int k=i+1;k<a.length;k++)
{
d[i] *= a[k];
}
}
for(int i=0;i<a.length;i++)
{
b[i] = c[i]*d[i];
}
}
}