【双指针】——左、右指针

  • 左右指针在数组中实际是指两个索引值, 初始化为 left = 0, right =nums.length - 1 。

二分搜索

int binarySearch(int[] nums, int target) {
	int left = 0;
	int right = nums.length - 1;

	while(left <= right) {
		int mid = (right + left) / 2;
		if(nums[mid] == target)
			return mid;
		else if (nums[mid] < target)
			left = mid + 1;
		else if (nums[mid] > target)
			right = mid - 1;
	} 
	return -1;
}

两数之和

只要数组有序, 就应该想到双指针技巧

int[] twoSum(int[] nums, int target) {
	int left = 0, right = nums.length - 1;
	while (left < right) {
		int sum = nums[left] + nums[right];
		if (sum == target) {
		// 题要求的索引是从 1 开始的
		return new int[]{left + 1, right + 1};
		} else if (sum < target) {
			left++; // 让 sum 大一点
		} else if (sum > target) {
			right--; // 让 sum小一 点
		}
	} 
	return new int[]{-1, -1};
}

哈希表

    //方法二
        //使用了hashMap,降低了时间复杂度,时间复杂度为O(n)
        HashMap<Integer,Integer> map = new HashMap<>();//用一个hashMap储存值和值的下标,如果map中不包含该数值则把数值压入map中,包含的话直接返回
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])){
                return new int[]{map.get(target - nums[i]),i};
            }
            map.put(nums[i],i);
        }
        return null;


反转数组

void reverse(int[] nums) {
	int left = 0;
	int right = nums.length - 1;
	while (left < right) {
		// swap(nums[left], nums[right])
		int temp = nums[left];
		nums[left] = nums[right];
		nums[right] = temp;
		left++; right--;
	}
}

反转链表

public ListNode reverseList(ListNode head) {
        ListNode cur = head,pre = null;
        while (cur != null){
            ListNode tmp = cur.next;    //  缓存后继节点 cur.next
            cur.next = pre;             //修改next引用指向
            pre = cur;                  //pre暂存cur
            cur = tmp;                  //cur访问下一个节点
        }
        return pre;
    }

滑动窗口法

实际上是快慢指针在数组上的应用,可以解决一大类字符串匹配的问题

posted @ 2021-03-08 17:30  your_棒棒糖  阅读(57)  评论(0编辑  收藏  举报