第十二题:树值的整数次方
题目描述:
给定一个double类型的浮点数base和int类型的整数exponent。求base的exponent次方。
思路:
这个题目主要的考点一是base, exponent都有0,负数,正数的情况,二是base的exponent次方可以用o(logN)的时间复杂度计算得到。
代码:
public class Solution {
public double Power(double base, int exponent) {
if (equal(base, 0.0)){
return 0;
}
if (exponent == 0){
return 1;
}
boolean flag = false;
if(exponent < 0){
flag = true;
exponent = -exponent;
}
double ret = Power2(base, exponent);
return flag ? 1/ret : ret;
}
public double Power2(double base, int exponent) {
if(exponent == 1) {
return base;
}
double tmp = Power2(base, exponent>>1);
tmp *= tmp;
if((exponent & 0x1) == 1) {//奇数
tmp *= base;
}
return tmp;
}
public boolean equal(double num1, double num2){
if(Math.abs(num1-num2)<=0.0000001){
return true;
}
return false;
}
}
第十三题:调整数组顺序使奇数位与偶数前面
题目描述:
输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。
思路:
因为要保持相对位置不变,则只能用o(n^2)的时间复杂度来求解此题,就是把整个数列扫一遍,遇到偶数就把此偶数对应位置以及其之后的数往前挪一位,把偶数放到最后一位。
代码:
public class Solution {
public void reOrderArray(int [] array) {
if (array == null || array.length == 0 ||
array.length == 1) {
return ;
}
int len = array.length;
int index = 0;
for (int i = 0; i < len; i++) {
if ((array[index] & 0x1) == 0) {//偶数
int tmp = array[index];
for (int j = index; j < len - 1; j++) {
array[j] = array[j+1];
}
array[len-1] = tmp;
}else{
index ++;
}
}
}
}
补充:
在数组长度非常大的时候,可以考虑用类似冒泡排序的做法,具体思路看代码吧。
public class jioushupaixu {
public static void sort(int[] input) {
if (input== null || input.length == 0 ||
input.length == 1) {
return ;
}
int count = 0;
for (int i = 0; i < input.length; i++) {
if ((input[i] & 0x1) == 0) {// 偶数
count++;
}
}
if (count == 0 || count == input.length) {
return;
}
int index = 0;
while ((input[index] & 0x1) == 1) {// 奇数
index++;
}
for (int i = 0; i < input.length; i++) {
for (int j = index; j < input.length - 1; j++) {
if (((input[j] & 0x1) ^ (input[j + 1] & 0x1)) == 1) {// 前后两位奇偶性不同
swap(input, j, j + 1);
}
}
while ((input[index] & 0x1) == 1) {// 奇数
index++;
}
}
}
public static void swap(int[] input, int a, int b) {
int tmp = input[a];
input[a] = input[b];
input[b] = tmp;
}
}
第十四题:链表中倒数第k个结点
题目描述:
输入一个链表,输出该链表中倒数第k个结点。
思路:
这个题目记得当时保研考试也出现过,很简单,初始化两个指针p1,p2,p1先走k步,p2不动,然后p2与p1一起走,当p1走到null时,p2所指的ListNode就是倒数第k个结点。
代码:
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindKthToTail(ListNode head,int k) {
if (head == null || k<0) {
return null;
}
ListNode p1 = head;
ListNode p2 = head;
for (int i = 0; i < k; i++) {
if (p1 != null) {
p1 = p1.next;
}else {
return null;
}
}
while (p1 != null) {
p1 = p1.next;
p2 = p2.next;
}
return p2;
}
}