zoukankan      html  css  js  c++  java
  • Two Sum

    源代码:

    import java.util.Arrays;
    public class Solution {
        public int[] twoSum(int[] numbers, int target) {
            int[] results = new int[2];
            int len = numbers.length;
            Node[] nodes = new Node[len];
            for (int i = 0; i < len; i++) {
                nodes[i] = new Node(i + 1, numbers[i]);
            }
            /*
            Node tempNode = null;
            
            for (int i = 0; i < len; i++) {
                for (int j = 0; j < len - 1 - i; j++) {
                    if (nodes[j].value > nodes[j + 1].value) {
                        tempNode = nodes[j];
                        nodes[j] = nodes[j + 1];
                        nodes[j + 1] = tempNode;
                    }
                }
            }
            */
            Arrays.sort(nodes);
    
            int key = -1, index = -1;
            for (int i = 0; i < len; i++) {
                key = target - nodes[i].value;
                index = binarySearch(nodes, key);
                if (index != -1 && i != index) {
                    if (nodes[i].index < nodes[index].index) {
                        results = new int[] { nodes[i].index, nodes[index].index };
                    } else {
                        results = new int[] { nodes[index].index, nodes[i].index };
                    }
                    return results;
                }
            }
    
            return results;
        }
        
        public int binarySearch(Node[] nodes, int key) {
            int left = 0, right = nodes.length - 1, mid = (left + right) >> 1;
    
            while (left <= right) {
                mid = (left + right) >> 1;
                if (nodes[mid].value == key) {
                    return mid;
                } else if (nodes[mid].value > key) {
                    right = mid - 1;
                } else {
                    left = mid + 1;
                }
            }
            return -1;
        }
    
        class Node implements Comparable<Node>{
            int index;
            int value;
    
            public Node() {
            }
    
            public Node(int index, int value) {
                this.index = index;
                this.value = value;
            }
            @Override
            public int compareTo(Node node) {
    
                if (this == node) {
                    return 0;
                }
                return this.value - node.value;
            }
        }
    }
  • 相关阅读:
    vSphere存储
    NFS服务器搭建
    windows下部署 ISCSI存储
    使用命令修改ip地址
    磁盘操作
    OpenFiler安装与基本配置
    OSPF系列
    NAT
    VLAN系列
    Linux下DNS服务器的基本搭建
  • 原文地址:https://www.cnblogs.com/xiaoxian1369/p/3631933.html
Copyright © 2011-2022 走看看