1. 数组循环移位,在这个数组中查找相应的数字
//题目:
//请完成以下算法,给定一个循环有序的数组,在这个数组中找到指定元素,找到的话返回下标,没有找到返回-1。
//该数据的特点是它是一个单调递增的数组向右循环移位形成的。
//举例说明,原数组是[4, 8, 13, 20, 23, 34, 41, 52]经过向右循环移位后形成的数组可能是[23, 34, 41, 52, 4, 8, 13, 20],也可能是[4, 8, 13, 20, 23, 34, 41, 52]
public class Solution {
public int indexOf(int[] array, int target) {
int length = array.length;
int left = 0;
int right = length-1;
int mid = (left+right)/2;
while(left <= right) {
if(array[mid] == target) return mid;
if(array[left] == target) return left;
if(array[right] == target) return right;
//如果左边有序
if(array[left] < array[mid]) {
if(target > array[left] && target < array[mid]) {
++left;
right = mid -1;
} else {
left = mid + 1;
--right;
}
}
//右边有序
else {
if(target > array[mid] && target < array[right]) {
left = mid + 1;
--right;
} else {
++left;
right = mid - 1;
}
}
mid = (left + right)/2;
}
return -1;
}
}
class Test {
public static void main(String[] args) {
Solution test = new Solution();
int[] array = {23, 34, 41, 52, 4, 8, 13, 20};
int n = test.indexOf(array, 21);
System.out.println(n);
}
}
2. 字符串的编解码
//题目:
//请完成右侧函数,该函数功能是解密一个给定字符串,解密的规则是将两个数字间(前面没有数字的情况下算开头和数字间)的字符串重复数字次数,数字不会超过int表示的范围。
//比如a2bc3d1,解密后字符串是aabcbcbcd
//思路,记住每次的子串的起始位置,并算出这个子串的重复次数,复制到结果串里即可
public class Solution {
public String decode(String str) {
String result = new String();
int size = str.length();
int begin = 0;
int end = 0;
int count = 0;
for(int i=0; i <= size-1; ++i) {
if(str.charAt(i) > '0' && str.charAt(i) < '9') {
count = count * 10 + (str.charAt(i) - '0');
if(i == size-1 || str.charAt(i+1) < '0' || str.charAt(i+1) > '9') {
for(int j=0; j < count; ++j) {
result += str.substring(begin, end);
}
count = 0;
begin = i+1;
end = i+1;
}
}
else
++end;
}
return result;
}
}
class Test {
public static void main(String[] args) {
Solution test = new Solution();
String str = "a2bc3d13";
String result = test.decode(str);
System.out.println(result);
}
}
//test
//a2bc3d1
//a2bc3d13