数据结构

本文详细介绍了几种经典的排序算法,如选择排序、插入排序和冒泡排序,并提供了对应的Java实现。此外,还探讨了二分查找在不同场景的应用,包括查找元素存在性、找到最接近的值以及局部最小值的定位。文章还包括了数据结构的实现,如双向链表反转、环形数组、最小栈和用两个栈实现队列等。
摘要由CSDN通过智能技术生成

SelectionSort

public class SelectionSort {

	public static void selectionSort(int []arr) {
		if (arr == null || arr.length < 2){
			return;
		}
		for (int i = 0; i < arr.length - 1; i++){
			int minIndex = i;
			for (int j = i + 1; j < arr.length; j++){
				minIndex = arr[minIndex] < arr[j] ? minIndex : j;
			}
			swap(arr, i, minIndex);
		}

	}

	public static void swap(int[] arr, int i, int j){
		arr[i] = arr[i] ^ arr[j];
		arr[j] = arr[i] ^ arr[j];
		arr[i] = arr[i] ^ arr[j];
	}

} 

问题:这一步搞错了

minIndex = arr[minIndex] < arr[j] ? minIndex : j;

InsertionSort

public class InsertionSort {
	
	public static void insertionSort(int []arr) {
		if (arr == null || arr.length < 2){
			return;
		}
		for(int i=0; i < arr.length; i++) {
			for(int j = i-1; j >= 0 && arr[j] > arr[j+1]; j—){
				swap(arr,j, j+1);
			}
		}
	}

	public static void swap(int[] arr, int i, int j){
		arr[i] = arr[i] ^ arr[j];
		arr[j] = arr[i] ^ arr[j];
		arr[i] = arr[i] ^ arr[j];
	} 

}

BubbleSort

public class BubbleSort {

	public static void bubbleSort(int []arr) {
		if (arr == null || arr.length < 2) {
			return;
		}
		for (int e = arr.length - 1; e > 0; e- -) {
			boolean flag = true;
			for (int i= 0; i< e; i++) {
				if (arr[i] > arr[i+1]) {
					swap(arr, i, j);
					flag = false;
				}
			}
			if (flag) {
				break;
			}
		}
	}

	public static void swap(int[] arr, int i, int j){
		arr[i] = arr[i] ^ arr[j];
		arr[j] = arr[i] ^ arr[j];
		arr[i] = arr[i] ^ arr[j];
	} 

}

BSExist

二分查找某个数是否存在

public class BSExist {

	public static boolean  exist (int []sortedArr, int num) {
		if (sortedArr ==null || sortedArr.length == 0) {
			return;
		}
		int L = 0;
		int R = sortedArr.length - 1;
		int min = 0;
		while(L < R) {
			mid = L + ((R - L) >> 1);
			if (sortedArr[mid] == num) {
				return true;
			}
			else if (sortedArr[mid] > num) {
				R = mid - 1;
			}
			else{
				L = mid + 1;
			}
		}
		return sortedArr[L] == num;
	}
	


}
问题:这一步差点忘了
return sortedArr[L] == num;

BSNearLeft

在arr上,找满足大于等于value的最左位置

public class BsNearLeft {
	
	public static int nearestIndex(int []arr, int value) {
		int L = 0;
		int R = arr.length - 1;
		int index = -1;
		while (L < R) {
			mid = L + ((R - L) >> 2);
			if (arr[mid] >= value) {
				index = value;
				R = mid - 1;
			}
			else{
				L = mid + 1;
			}
		}
		return index;
	}

}

BSNearRight

在arr上,找满足小于等于value的最右位置

public class BSNearRight {

	public static int nearestIndex(int []arr, int value) {
		int L = 0;
		int R = arr.length - 1;
		int index = -1;
		while (L < R) {
			int mid = L + ((R - L) >> 1);
			if (arr[mid] <= value){
				index = mid;
				L = mid + 1;
			} else{
				R = mid - 1;
			}
		}
		return index;
	}

}

BSAwesome

Arr无序,任意两个相邻位置不等,返回一个局部最小的位置

public class BSAwesome {

	public static int getLessIndex(int []arr) {
		if (arr == null || arr.length == 0) {
			return -1;
		}
		if (arr.length == 1 || arr[0] <arr[1]) {
			return 0;
		}
		if (arr[arr.length - 2] > arr[arr.length - 1]) {
			return arr.length - 1;
		}
		int L = 1;
		int R = arr.length - 2;
		int mid = 0;
		while(L < R) {
			mid = L + ((R - L) >> 1);
			if (arr[mid] > arr[mid - 1]) {
				R = mid - 1;
			}
			if (arr[mid] < arr[mid + 1]) {
				L = mid + 1;
			}else {
				return mid;
			}
		}
		return L;
	}

}
问题:1、思考不全面
		if (arr == null || arr.length == 0) {
			return -1;
		}
		if (arr.length == 1 || arr[0] <arr[1]) {
			return 0;
		}

			2、思考不全面
			else {
				return mid;
			}

EvenTimesOddTimes

arr中,只有一种数,出现了奇数次,找出打印
arr中,只有两种数,出现了奇数次,找出打印
提取出一个数最右侧的1

public class EvenTimesOddTimes {

	// arr中,只有一种数,出现了奇数次,找出打印
	public static void printOddTimesNum1(int [arr]) {
		int err = 0;
		for (int i = 0; i < arr.length; i++) {
			err ^= arr[i];
		}
		System.out.println(err);
	}
	
	// arr中,只有两种数,出现了奇数次,找出打印
	public static void printOddTimesNum2(int []arr) {
		int err = 0;
		for (int i = 0; i < arr.length; i++) {
			err ^= arr[i];
		}
		// 提取出一个数最右侧的1   N: 对N取反加1然后和N &运算
		int rightOne = err & (~eor + 1);

		int err2 = 0;
		for (int i = 0; i < arr.length; i++) {
			if (arr[i] & rightOne != 0) {
				err2 ^= arr[i];
			}
		}
		System.out.println(err2 + “” + err2 ^ err);
	}



}

ReverseList

public class ReverseList {

	public static class Node {
		public int value;
		public Node next;

		public Node(int value) {
			this.value = value;
		}
	}

	public static void DoubleNode {
		public int value;
		public DoubleNode last;
		public DoubleNode next;

		public DoubleNode(int value){
			this.value = value;
		}
	}

	public static Node reverseLinkedList(Node head) {
		Node pre = null;
		Node next = null;
		while(head != null) {
			next = head.next;
			head.next = pre;
			pre = head;
			head = next;
		}
		return pre;
	}
	
	public static DoubleNode reverseDoubleList(DoubleNode head) {
		DoubleNode pre = null;
		DoubleNode next = null;
		while(head != null){
			next = head.next;
			head.next = pre;
			head.last = next;
			pre = head;
			head = next;
		}
		return pre;
	}

} 

DeleteGivenValue

public class DeleteGivenValue{

	public static class Node {
		public int value;
		public Node next;

		public Node(int value) {
			this.value = value;
		}
	}

	public static Node removeValue(Node head, int num) {
		while(head != null) {
			if (head.value == num){
				head = head.next;
			}
		}
		pre = head;
		cur = head;
		while (cur != null) {
			if (cur.value == num) {
				pre.next = cur.next;
			}else {
				pre = cur;
			}
			cur = cur.next;
		}
	}

}
问题:不管相等不相等,cur都要来到下一个位置
		while (cur != null) {
			if (cur.value == num) {
				pre.next = cur.next;
			}else {
				pre = cur;
			}
			cur = cur.next;
		}

RingArray

public class  RingArray {

	public static class myQueue {
		private int[] arr;
		private int pushi;
		private int polli;
		private int size;
		private final int limit;

		public myQueue(int limit) {
			arr = new int[limit];
			pushi = 0;
			polli = 0;
			this.limit = limit;
 		}
		
		public void push(int value) {
			if ( size == limit) {
				throw new RuntimeException(“is MAX”);
			}
			size ++;
			arr[pushi] = value;
			pushi = nextIndex(pushi); 
		}

		public int pop() {
			if ( size == 0) {
				throw new RuntimeException(“is null”);
			}
			size —;
			int ans = arr[polli];
			polli = nextIndex(polli); 
		}
		
		public int nexIndex(int i) {
			return i < limit - 1 ? i + 1 : 0;
		}



	}

}

GetMinStack

public class GetMinStack {

	public class MyStack1 {
		private Stack<Integer> stackData;
		private Stack<Integer> stackMin;

		public MyStack1() {
			this.stackData = new Stack<Integer>();
			this.stackMin = new Stack<Integer>();
		}

		public void push(int newNum) {
			if (this.stackMin.isEmpty()){
				this.stackMin.push(newNum);
			}else if (this.getMin() >= newNum) {
				this.stackMin.push(newNum);
			}
			this.stackData.push(newNum);
		}

		public int pop() {
			if (this.stackData.isEmpty()) {
				throw new RuntimeException(“”);
			}
			int value = this.stackData.pop();
			if (value == this.getMin()) {
				this.stackMin.pop();
			}
			return value;
		}

		public int getMin() {
			if (this.stackMin.isEmpty()) {
				throw new RuntimeException(“stack is empty”);
			}
			return this.stackMin.peek();
		}	


	}

	

}

TwoStacksImplementQueue

public class TwoStacksImplementQueue {

	public static class TwoStacksQueue {
		public Stack<Integer> stackPush;
		public Stack<Integer> stackPop;

		public TwoStacksQueue() {
			stackPush = new Stack<Integer>();
			stackPop = new Stack<Integer>();
		}

		private void pushToPop() {
			if (stackPop.empty()) {
				while (!stackPush.empty()) {
					stackPop.push(stackPush.Pop());
				}
			}
		}

		public void add (int PushInt) {
			stackPush.push(PushInt);
			pushToPop();
		}
		
		public int poll (){
			if (stackPop.empty() && stackPush.empty()) {
				throw new RuntimeException(“null”);
			}
			pushToPop();
			return stackPop.pop();
		}
		
		public int peek() {
			if (stackPop.empty() && stackPush.empty()) {
				throw new RuntimeException(“null”);
			}
			pushToPop();
			return stackPop.peek();
		}


	}


}

TwoQueueImplementStack

offer poll peek

public class  TwoQueueImplementStack {

	public static class TwoQueueStack<T> {
		public Queue<T> queue;
		public Queue<T> help;

		public TwoQueueStack(T) {
			queue = new LinkedList<T>();
			help = new LinkedList<>();
		}

		public void push(T value) {
			queue.offer(value);
		}

		public T poll() {
			while (queue.size() > 1) {
				help.offer(queue.poll());
			}
			T ans = queue.poll();
			Queue<T> tmp = queue;
			queue = help;
			help = tmp;
			return ans;
		}

		public T peek() {
			while (queue.size() > 1) {
				help.offer(queue.poll());
			}
			T ans = queue.poll();
			help.offer(ans);
			Queue<T> tmp = queue;
			queue = help;
			help = tmp;
			return ans;
		}

		public boolean isEmpty() {
			return queue.isEmpty();
		}



	}

}

MergeSort

public class MergeSort {

	public static void mergeSort(int[] arr) {
		if (arr == null || arr.length < 2) {
			return;
		}
		process(arr, 0, arr.length - 1);
	
	}

	public static void process(int[] arr, int L, int R) {
		if (L = R) {
			return;
		}
		int mid = L + ((R - L) >> 1);
		process(arr, L, mid);
		process(arr, mid, R);
		merge(arr, L, mid, R);
	}

	public static void merge(int[]  arr, L, mid, R) {
		int[] help = new int[R-L+1];
		int i = 0;
		int p1 = L;
		int p2 = mid + 1;
		while (p1 <= mid && p2 <= R) {
			help[i++] = arr[p1] <= arr[p2] ? arr[p1++] : arr[p2++];
		}
		while (p1 <= mid) {
			help[i++] = arr[p1++];
		}
		while (p2 <= R) {
			help[i++] = arr[p2++];
		}
		for (i =0; i < help.length; i ++) {
			arr[L + i] = help[i];
		}
	}






	
	public static void main(String[] args) {}

}

SmallSum

public class SmallSum {

	public static int smallSum(int[] arr) {
		if (arr == null || arr.length < 2) {
			return 0;
		}
		process(arr, 0, arr.length - 1);
	}
	
	public static int process(int[] arr, int L, int R) {
		if (L=R) {
			return 0;
		}
		int mid = l + ((r - l) >> 1);
		return 
				process(arr, l, mid) 
				+ 
				process(arr, mid + 1, r) 
				+ 
				merge(arr, l, mid, r);
	}

	public static int merge(int[]  arr, L, mid, R) {
		int[] help = new int[R-L+1];
		int i = 0;
		int p1 = L;
		int p2 = mid + 1;
		int res = 0;
		while (p1 <= mid && p2 <= R) {
			res += arr[p1] < arr[p2] ? arr[p1] * (R - p2 + 1) : 0;
			help[i++] = arr[p1] < arr[p2] ? arr[p1++] : arr[p2++];
		}
		while (p1 <= mid) {
			help[i++] = arr[p1++];
		}
		while (p2 <= R) {
			help[i++] = arr[p2++];
		}
		for (i =0; i < help.length; i ++) {
			arr[L + i] = help[i];
		}
	}


}

ReversePair

public class ReversePair {

	public static int reversePair(int[] arr) {
		if (arr == null || arr.length < 2) {
			return 0;
		}
		return process(arr, 0, arr.length - 1);
	}

	public static int process(int[] arr, int L, int R) {
		if (L=R) {
			return 0;
		}
		int mid = l + ((r - l) >> 1);
		return 
				process(arr, l, mid) 
				+ 
				process(arr, mid + 1, r) 
				+ 
				merge(arr, l, mid, r);
	}

	public static int merge(int[]  arr, L, mid, R) {
		int[] help = new int[R-L+1];
		int i = 0;
		int p1 = L;
		int p2 = mid + 1;
		int res = 0;
		while (p1 <= mid && p2 <= R) {
			res += arr[p1] > arr[p2] ? mid - p1 + 1 : 0;
			help[i++] = arr[p1] >= arr[p2] ? arr[p1++] : arr[p2++];
		}
		while (p1 <= mid) {
			help[i++] = arr[p1++];
		}
		while (p2 <= R) {
			help[i++] = arr[p2++];
		}
		for (i =0; i < help.length; i ++) {
			arr[L + i] = help[i];
		}
	}

	


} 

quickSort

public class QuickSort {

	public static void quickSort(int[] arr) {
		if (arr == null || arr.length < 2) {
			return;
		}
		process3(arr, 0, arr.length - 1);
	}

	public static void process3(int[] arr, int L, int R) {
		if (L >= R) {
			return;
		}
		swap(arr, L + (int) (Math.random() * (R - L + 1)), R);
		int[] equalArea = partition(arr, L, R);
		process3(arr, L, equalArea[0] - 1);
		process3(arr, equalArea[1] + 1, R);
	}

	public static int[] partition(int[] arr, int L, int R) {
		if (L > R) { // L...R L>R
			return new int[] { -1, -1 };
		}
		if (L == R) {
			return new int[] { L, R };
		}
		int less = L - 1; // < 区 右边界
		int more = R; // > 区 左边界
		int index = L;
		while(index < more) {
			if (arr[index] == arr[R]) {
				index++;
			} else if (arr[index] < arr[R]) {					
				swap(arr, index++, ++less);
			} else {
				swap(arr, index, --more);
			}
		}
		swap(arr, more, R);
		return new int[] { less + 1, more };
	}

}

HeapSort

public class HeapSort {

	public static void heapSort(int[] arr) {
		if (arr == null || arr.length < 2) {
			return;
		}

		// O(N)
		for (int i = arr.length - 1; i >= 0; i--) {
			heapify(arr, i, arr.length);
		}

		int heapSize = arr.length;
		swap(arr, 0, --heapSize);
		// O(N*logN)
		while (heapSize > 0) { // O(N)
			heapify(arr, 0, heapSize); // O(logN)
			swap(arr, 0, --heapSize); // O(1)
		}
	}

	public static void heapInsert(int[] arr, int index) {
		while (arr[index] > arr[(index - 1) / 2]) {
			swap(arr, index, (index - 1) / 2);
			index = (index - 1) / 2;
		}
	}

	public static void heapify(int[] arr, int index, int heapSize) {
		int left = index * 2 + 1; 
		while (left < heapSize) {
			int largest = left + 1 < heapSize && arr[left + 1] > arr[left] ? left + 1 : left;
			largest = arr[largest] > arr[index] ? largest : index;
			if (largest == index) {
				break;
			}
			swap(arr, largest, index);
			index = largest;
			left = index * 2 + 1;
		}
	}

	public static void swap(int[] arr, int i, int j) {
		int tmp = arr[i];
		arr[i] = arr[j];
		arr[j] = tmp;
	}
}

SortArrayDistanceLessK


public class SortArrayDistanceLessK {

	public static void sortedArrDistanceLessK(int[] arr, int k) {
		if (k == 0) {
			return;
		}
		// 默认小根堆
		PriorityQueue<Integer> heap = new PriorityQueue<>();
		int index = 0;
		// 0...K
		for (; index <= Math.min(arr.length - 1, k); index++) {
			heap.add(arr[index]);
		}
		int i = 0;
		for (; index < arr.length; i++, index++) {
			heap.add(arr[index]);
			arr[i] = heap.poll();
		}
		while (!heap.isEmpty()) {
			arr[i++] = heap.poll();
		}
	}
}

RecursiveTraversalBT

public class RecursiveTraversalBT {

	public static class Node {
		public int value;
		public Node left;
		public Node right;

		public Node(int v) {
			value = v;
		}
	}

	public static void f(Node head) {
		if (head == null) {
			return;
		}
		// 1
		f(head.left);
		// 2
		f(head.right);
		// 3
	}

}

UnRecursiveTraversalBT

public class UnRecursiveTraversalBT {

	public static class Node {
		public int value;
		public Node left;
		public Node right;

		public Node(int v) {
		
	}
	// 先序遍历
	public static void pre(Node head) {
		if (head != null) {
			Stack<Node> stack = new Stack<Node>();
			stack.push(head);
			if (!stack.isEmpty()) {
				head = stack.pop();
				System.out.print(head.value + " ");
				if (head.right != null) {
					stack.push(head.right);
				}
				if (head.left != null) {
					stack.push(head.left);
				}
			}
		}
	}

	// 中序遍历    左边界
	public static void in(Node cur) {
		if (cur != null) {
			Stack<Node> stack = new Stack<Node>();
			while (!stack.isEmpty() || cur != null) {
				if (cur != null) {
					stack.push(cur);
					cur = cur.left;
				}else{
					cur = stack.pop();
					System.out.print(cur.value + " ");
					cur = cur.right;
				}
			}
		}
	}
	
	// 后序遍历
	public static void pos1(Node head) {
		if (head != null) {
			Stack<Node> s1 = new Stack<Node>();
			Stack<Node> s2 = new Stack<Node>();
			s1.push(head);
			while(!s1.isEmpty()) {
				head = s1.pop();
				s2.push(head);
				if (head.left != null) {
					s1.push(head.left);
				}
				if (head.right != null) {
					s1.push(head.right);
				}
			}
		}
		while (!s2.isEmpty()) {
				System.out.print(s2.pop().value + " ");
			}
	}
	
	//使用一个栈实现后序遍历
	public static void pos2(Node h) {
		if (h != null) {
			Stack<Node> stack = new Stack<Node>();
			stack.push(h);
			Node c = null;
			while (!stack.isEmpty()) {
				c = stack.peek();
				if (c.left != null && h != c.left && h != c.right) {
					stack.push(c.left);
				} else if (c.right != null && h != c.right) {
					stack.push(c.right);
				} else {
					System.out.print(stack.pop().value + " ");
					h = c;
				}
			}
		}
		System.out.println();
	}



}

LevelTraversalBT

public class LevelTraversalBT {

	public static class Node {
		public int value;
		public Node left;
		public Node right;

		public Node(int v) {
			value = v;
		}
	}

	public static void level(Node head) {
		if (head == null) {
			return;
		}
		Queue<Node> queue = new LinkedList<>();
		queue.add(head);
		while (!queue.isEmpty()) {
			Node cur = queue.poll();
			System.out.println(cur.value);
			if (cur.left != null) {
				queue.add(cur.left);
			}
			if (cur.right != null) {
				queue.add(cur.right);
			}
		}
	}

}

TreeMaxWidth

public class TreeMaxWidth {

	public static class Node {
		public int value;
		public Node left;
		public Node right;

		public Node(int data) {
			this.value = data;
		}
	}

	public static int maxWidthUseMap(Node head) {
		if (head == null) {
			return 0;
		}
		Queue<Node> queue = new LinkedList<>();
		queue.add(head);
		// key 在 哪一层,value
		HashMap<Node, Integer> levelMap = new HashMap<>();
		levelMap.put(head, 1);
		int curLevel = 1; // 当前你正在统计哪一层的宽度
		int curLevelNodes = 0; // 当前层curLevel层,宽度目前是多少
		int max = 0;
		while (!queue.isEmpty()) {
			Node cur = queue.poll();
			int curNodeLevel = levelMap.get(cur);
			if (cur.left != null) {
				levelMap.put(cur.left, curNodeLevel + 1);
				queue.add(cur.left);
			}
			if (cur.right != null) {
				levelMap.put(cur.right, curNodeLevel + 1);
				queue.add(cur.right);
			}
			if (curNodeLevel == curLevel) {
				curLevelNodes++;
			} else {
				max = Math.max(max, curLevelNodes);
				curLevel++;
				curLevelNodes = 1;
			}
		}
		max = Math.max(max, curLevelNodes);
		return max;
	}

	public static int maxWidthNoMap(Node head) {
		if (head == null) {
			return 0;
		}
		Queue<Node> queue = new LinkedList<>();
		queue.add(head);
		Node curEnd = head; // 当前层,最右节点是谁
		Node nextEnd = null; // 下一层,最右节点是谁
		int max = 0;
		int curLevelNodes = 0; // 当前层的节点数
		while (!queue.isEmpty()) {
			Node cur = queue.poll();
			if (cur.left != null) {
				queue.add(cur.left);
				nextEnd = cur.left;
			}
			if (cur.right != null) {
				queue.add(cur.right);
				nextEnd = cur.right;
			}
			curLevelNodes++;
			if (cur == curEnd) {
				max = Math.max(max, curLevelNodes);
				curLevelNodes = 0;
				curEnd = nextEnd;
			}
		}
		return max;
	}
}

SuccessorNode

public class SuccessorNode {

	public static class Node {
		public int value;
		public Node left;
		public Node right;
		public Node parent;

		public Node(int data) {
			this.value = data;
		}
	}

	public static Node getSuccessorNode(Node node) {
		if (node == null) {
			return node;
		}
		if (node.right != null) {
			return getLeftMost(node.right);
		} else { // 无右子树
			Node parent = node.parent;
			while (parent != null && parent.right == node) { // 当前节点是其父亲节点右孩子
				node = parent;
				parent = node.parent;
			}
			return parent;
		}
	}

	public static Node getLeftMost(Node node) {
		if (node == null) {
			return node;
		}
		while (node.left != null) {
			node = node.left;
		}
		return node;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AloneDrifters

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值