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;
        }
    }
}

 

posted @ 2014-03-28 23:17  qingyezhu  阅读(132)  评论(0编辑  收藏  举报