题目来自LeetCode、《编程之法-面试和算法心得》
给定一个整数数组 nums?和一个目标值 target,请你在该数组中找出和为目标值的那?两个?整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
void testTwoNum(){
int[] input = new int[]{2, 7, 11, 15};
int[] result = twoSum(input, 9);
System.out.println(Arrays.toString(result));
}
/**
* 思路:
* 一遍hash算法
* 通过遍历将数组中的值作为hashmap的key,下标作为hashmap的value
* 时间、空间复杂度均为O(n)
* @param nums
* @param target
* @return
*/
int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap();
for(int i = 0; i < nums.length; i++){
int subTarget = target - nums[i];
if(map.containsKey(subTarget)){
return new int[]{map.get(subTarget), i};
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("找不到两数之和");
}
给定一个字符串,要求将字符串前面的若干个字符移动到字符串尾部
* 例如:将abcdef的前3个字符abc移动到字符串尾部,输出defabc
/**
* 给定一个字符串,要求将字符串前面的若干个字符移动到字符串尾部
* 例如:将abcdef的前3个字符abc移动到字符串尾部,输出defabc
*
* 思路:
* 1、把字符串分成两个部分前面3个字符,后面字符 abc def
* 2、把两个部分字符串分别反转 cbafed
* 3、整体反转defabc
* 时间复杂度为O(n)
* 空间复杂度为O(1)
*/
private void reverseString(char[] chars, int from, int to){
while (from < to){
char temp = chars[from];
chars[from++] = chars[to];
chars[to--] = temp;
}
}
public void testA(){
String str = "abcdef";
int n = 3;
char[] chars = str.toCharArray();
reverseString(chars, 0, n - 1);
reverseString(chars, n, chars.length - 1);
reverseString(chars, 0, chars.length - 1);
System.out.println(new String(chars));
}
原文:https://www.cnblogs.com/lspkenney/p/12419864.html